C# Snippet Tutorial - How to Get an Enum from a Number

Skill

C# Snippet Tutorial - How to Get an Enum from a Number

Posted in:

To continue our snippet tutorial series, here's a quick tutorial on how to convert an integer to an enum. This is useful when you've got a number, either from a file or transferred over a socket, and you want to convert that number to an enum.

What we're going to create is a generic method that can convert a number to any type of enum. I like using a generic method for this because now I can convert numbers to any type of enum using the same function and without having to cast the return value for each enum separately.

Here's the function that will be doing all the work:

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

This is a generic function that can convert a number to any type of enum. Let's see some sample code that makes use of this function. First, let's create some enums.

public enum DaysOfWeek
{
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
}

public enum MonthsInYear
{
   January,
   February,
   March,
   April,
   May,
   June,
   July,
   August,
   September,
   October,
   November,
   December
}

Now, let's see some code that uses NumToEnum.

int day = 3;
int month = 10;

DaysOfWeek d  = NumToEnum<DaysOfWeek>(day);
//d is now DaysOfWeek.Thursday

MonthsInYear m = NumToEnum<MonthsInYear>(month);
//m is now MonthsInYear.November

I know this is something I've needed on several occasions, so hopefully this will help you out as well. Leave any questions in the comments and we'll answer them as best we can.

Dog
08/31/2007 - 16:22

Am I doing something wrong, I get this error when I run the above code: "An object reference is required for the nonstatic field, method, or property 'Program.NumToEnum(int)"

reply

The Reddest
08/31/2007 - 16:31

It sounds like you're trying to reference NumToEnum like a static method of the class Program. You can make NumToEnum static by putting the 'static' keyword after 'public' and your code will probably compile. Otherwise you'll need a reference to the Program object for it to work:

Program p = new Program();
p.NumToEnum(int);

reply

Dog
08/31/2007 - 22:14

that worked. thx!

reply

Yuyama
10/20/2007 - 06:23

Your solution is cool!
If int number is out of enum member numbers (0 to 6 for DaysOfWeek for example,) how can I detect such an error?

reply

The Reddest
10/20/2007 - 11:38

You can use Enum.IsDefined to check and see if the enum exists before calling NumToEnum. IsDefined takes the value of the enum or the name of the enum has an argument. So you'll have something like:

if(Enum.IsDefined(typeof(DaysOfWeek), myNum)
{
  d = NumToEnum<DaysOfWeek>(myNum);
}
else
{
  //No enum for number myNum
}

This technique is explained in a little more depth in a follow up tutorial on getting an enum from a string.

reply

Dan
12/27/2008 - 18:39

How is this better than just casting to the enum? Like this:

int i = 3;
DaysOfWeek dow = (DaysOfWeek) i;
Console.WriteLine( dow ); // “Thursday”

reply

The Reddest
02/20/2009 - 10:56

It's not. I would recommend casting. Live and learn.

reply

greatonkar
03/19/2009 - 01:54

Cool... Works Fine! Thanks Dan

reply

Tom
03/19/2009 - 15:48

        public T GetEnum<T>(int number)
        {
            if (Enum.IsDefined(typeof(T), number))
                return (T)Enum.ToObject(typeof(T), number);
            else
                throw new ArgumentException(typeof(T).ToString() + "does not contain a value member = " + number.ToString());

        }

        public static T GetEnum<T>(string name)
        {
            if (Enum.IsDefined(typeof(T), name))
                return (T)Enum.Parse(typeof(T), name);
            else
                throw new ArgumentException(typeof(T).ToString() + "does not contain a value member = " + name);
        }

reply

Anonymous
08/07/2009 - 12:37

i thought casting comes with a hit to performance?

reply

The Reddest
08/07/2009 - 14:54

In some cases it can, however all casting does is invoke the conversion operator to convert the object to the new type. In the case of enums, the value is stored as a number internally anyway, so the conversion operator should be very quick.

reply

Dhejo Vanissery
03/04/2010 - 22:20

Enum.IsDefined is a performance killer....refer.
http://blogs.msdn.com/brada/archive/2003/11/29/50903.aspx

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors