Vadim's Weblog

Never stop learning.

Archive for October 19th, 2007

Enum Conversion.

Posted by Vadim on October 19, 2007

In this post I will demonstrate how to convert Enum To String, String To Enum, and Value to Enum.

First of all let us create an enumeration:

   1: enum Colors
   2: {
   3:     Blue = 1, 
   4:     Green = 2, 
   5:     Red = 4
   6: }

 

Convert Enum To String.

It seams that nothing can be easier.  We easily can use ToString() method to convert Enum to String.  It would work fine if we try to convert Colors.Green, Colors.Blue, or Color.Red.  However, what if we try to convert to String value like this:

   1: Colors myColor = Colors.Green | Colors.Blue;
   2: Console.WriteLine(myColor.ToString());

The output will be ‘3′ instead of ‘Blue, Green’.

There are two ways we can solve this problem:

We can just add FlagsAttribute to our enumeration.

   1: [FlagsAttribute]
   2: enum Colors
   3: {
   4:     Blue = 1, 
   5:     Green = 2, 
   6:     Red = 4
   7: }

Or another solution we can use Format() or ToString() methods with format “F” or “f”.

   1: Colors myColor = Colors.Green | Colors.Blue;
   2: Console.WriteLine(Enum.Format(typeof(Colors), myColor, "F"));
   3: Console.WriteLine(myColor.ToString("f"));

In case you decorated your enumertion with FlagsAttribute but want to output the value, use Format() or ToString() methods with format “D” for decimal form or “X” for hexadecimal one.

   1: Colors myColor = Colors.Green | Colors.Blue;
   2: // Format()
   3: Console.WriteLine(Enum.Format(typeof(Colors), myColor, "d"));
   4: Console.WriteLine(Enum.Format(typeof(Colors), myColor, "x"));
   5: // ToString()
   6: Console.WriteLine(myColor.ToString("D"));
   7: Console.WriteLine(myColor.ToString("X"));

The method with format “D” will output ‘3′ and with format “X” will give us ‘00000003′.

 

Convert String To Enum.

To convert String to Enum we just need to use Parse() method.

   1: public Colors String2Enum(string colorString)
   2: {
   3:     return (Colors)Enum.Parse(typeof(Colors), colorString);
   4: }

In the example above colorString must match case exactly.  There’s an override for Parse() method where you can ask to ignore case.

   1: public Colors String2Enum(string colorString)
   2: {
   3:     return (Colors)Enum.Parse(typeof(Colors), colorString, true);
   4: }

 

Convert Value To Enum.

We will use ToObject() method to convert value to Enum.

   1: public Colors Value2Enum(int colorValue)
   2: {
   3:     return (Colors)Enum.ToObject(typeof(Colors), colorValue);
   4: }

Update: Thanks to Omer Mor (see his comment below) who pointed out that we don’t have to invoke ToObject() method.  We can simply cast value to Enum type.

   1: public Colors Value2Enum(int colorValue)
   2: {
   3:     return (Colors) colorValue;
   4: }

kick it on DotNetKicks.com

Posted in Uncategorized | 2 Comments »