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.
Comments
Post a Comment