Enumeration string representations

F

Frank Moyles

If I have an enumeration:

enum SizeType
{
Tiny = 0,
Small,
Big,
Massive,
OMG
};


If I declare a variable like this:

SizeType myVar ;

I want to be able to print the appropriate string when I coerse/cast
myVar to string by calling the ToString() method - does anyone know how
I can "assign string values" to the enums (not technically correct), so
that the ff code:

SizeType myVar = SizeType.Tiny ;
//I'll just use C++ here, since I'm still learning C#
std::cout << "The enum mVar has a string representation of: '" <<
myVar.ToString() << "'\n";

Which should print the ff on stdio:

The enum mVar has a string representation of 'Tiny'
 
J

Jon Skeet [C# MVP]

Frank Moyles said:
If I have an enumeration:

enum SizeType
{
Tiny = 0,
Small,
Big,
Massive,
OMG
};


If I declare a variable like this:

SizeType myVar ;

I want to be able to print the appropriate string when I coerse/cast
myVar to string by calling the ToString() method

This happens automatically. Here's a short but complete program to
demonstrate it:

using System;

enum SizeType
{
Tiny = 0,
Small,
Big,
Massive,
OMG
}

class Test
{
static void Main()
{
SizeType myVar = SizeType.Tiny;

Console.WriteLine(myVar);
}
}

The output is "Tiny".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top