C# : Enum – Tricks & Tips

This is not a beginners tutorial for concept of Enum. Its is assumed that you are aware of the basic concepts of enum. Here I am presenting few advance level tricks and tips which programmers often need while working with enums. For basic tutorial on enum you can visit The C# Station Tutorial (Lesson 17: Enums) or msdn at http://msdn.microsoft.com/en-us/library/sbbt4032(VS.80).aspx

All enum instances in .net implicitly inherit the System.Enum type in the Base Class Library and hence we can use members of System.Enum with the instances of enums. There are few good functionalities available in System.Enum which are often required while working with enums and for manipulating  them. So lets have look on them one by one.

One of the common requirement is to cast the enum object to and fro between its integer and string values. Consider following sample code:

   1: public enum ColorSwatch

   2:    {

   3:        Black = 0,

   4:        Red = 1,

   5:        Green = 2,

   6:        Blue = 3,

   7:        Yellow = 4,

   8:        Orange = 5,

   9:        Pink = 6

  10:    }

int to Enum
This casting is the simple one.

      int colorCode = 2;

ColorSwatch selectedColor = (ColorSwatch)colorCode;

OR

ColorSwatch c;

c = (ColorSwatch )Enum.ToObject(typeof(ColorSwatch ), colorCode)

Enum to int
Once again this is a simple cast.

    ColorSwatch cs = ColorSwatch.Orange;

int c = (int)cs;

As per this code, integer variable c should now have integer value associated with Orange.

string to Enum
This cast is the tricky one and can be done in following way:

     string colorStr = “blue”;

bool ignoreCase = true;

ColorSwatch CC =    (ColorSwatch)Enum.Parse(typeof(ColorSwatch),

colorStr, ignoreCase);

But this code will throw an argument exception if the string value is either an empty string or only contains white space or is a name, but not one of the named constants defined for the enumeration. This exception can be avoided using IsDefined() method as follow:

if (Enum.IsDefined(typeof(ColorSwatch), colorStr))

{

ColorSwatch CC = (ColorSwatch)Enum.Parse(typeof(ColorSwatch),

colorStr,     ignoreCase);
}

Enum to string
Again this is the most simple one. Just using ToString() method gives us string value corresponding to the enum object.

Below are few other important functionalities available under System.Enum which are often useful :

Othre methods from System.Enum
  • Enum.GetName() :

Retrieves the name(string) of the constant in the specified enumeration that has the specified value.

  • Enum.GetNames() :Retrieves an array of string of the names of the constants in a specified enumeration. The elements of the return value array are sorted by the values of the enumerated constants.
  • Enum.GetValues() :Retrieves an array of the values of the constants in a specified enumeration.
Close Menu