Thursday, August 4, 2011

How to Get an Enum from a Number

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

No comments: