Enum coversion operations (int to enum, enum to int, string to enum, enum to string)

This post describes how can we convert enum into different data types. These are very often used operation. This is very simple to achieve thing. Let take an exmaple

public enum EmloyeeRole
{
  None = 0,
  Manager = 1,
  Admin = 2,
  Operator = 3
}

enum to int

To convert a enum to interger simply type cast the enum into integer

EmloyeeRole role = EmloyeeRole.Manager;
int roleInterger = (int)role;

int to enum

Same like above, simply type cast the integer to enum

int roleInterger = 2;
EmloyeeRole role = (EmloyeeRole)roleInterger;

string to enum

If you have string value and you want to type cast that into enum, then you can use Enum.Parse

string roleString = "Operator";
EmloyeeRole role = 
  (EmloyeeRole)Enum.Parse(typeof(EmloyeeRole), roleString);

enum to string

This is the simplest one, just use the ToString method of the enum

EmloyeeRole role = EmloyeeRole.Manager;
string roleString = role.ToString();

9 comment(S)


Visual C# Kicks on Jan 13, 2009 12:09 AM

The integer one is pretty useful. I would recommend staying away from String conversions since that's the point of using Enum in the first place. Although of course there are exceptions

Bee on Dec 13, 2009 07:30 AM

Can this be made as a generic function? where you pass the type and the value?


Ruben Ruiz on Feb 19, 2010 10:03 AM

public static T ConvertTo<T>(int number)
{
return (T)Enum.ToObject( typeof( T ), number );
}

public static T ConvertTo<T>(string value)
{

return (T)Enum.ToObject( typeof( T ), int.Parse(value));
}

adsad on Mar 25, 2013 02:01 PM

<script>alert(1);</script>

ALex on Jun 7, 2013 05:34 AM

Really generic version (for int, string and others):
static TEnum ConvertToEnum<TEnum>(object value) {
return (TEnum)Enum.Parse(typeof(TEnum), value.ToString());
}

navneet on Aug 9, 2013 10:28 AM

Nice Article Dear..

Hh- on Apr 1, 2014 12:39 AM

Ruben, your code is obtuse at best.

It's much easier to do the following:
(string)Enum.value
(int)Enum.value

Hh- on Apr 1, 2014 12:41 AM

Ruben, your code is obtuse at best.

It's much easier to do the following:
(string)Enum.value
(int)Enum.value

Amin on Apr 4, 2014 07:07 AM

Thanks, it was very usefull

Leave a comment