In the code sample, NumToEnum is a generic method that can convert an integer to any type of enum.
Function that will do all the work:
public T NumToEnum(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 example 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, see some code that uses NumToEnum.
int day = 3; int month = 10;
//d is now DaysOfWeek.Thursday DaysOfWeek d = NumToEnum(day);
//m is now MonthsInYear.November MonthsInYear m = NumToEnum(month);
|
No responses found. Be the first to respond and make money from revenue sharing program.
|