Welcome to Matt’s Blog, Please Keep to the Posted Speed Limit

Archive for August, 2007

Useful C#.Net Enum List Method

Posted by 2000mph on August 15, 2007

http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx

The blog above has a very useful bit of code for C#.Net that will convert a Enum definition into a List. This can be very useful, for instance to place all the values of an enum into a drop down list. I used it to check a cast from an int to enum was valid by checking it against the list.

public static List<T> EnumToList<T>()
{Type enumType = typeof(T);if (enumType.BaseType != typeof(Enum))throw new ArgumentException("T must be of type System.Enum");

return new List<T>(Enum.GetValues(enumType) as IEnumerable<T>);
}

Then used it like this to check a valid enum:

List<DayOfWeek> weekdays = EnumToList<DayOfWeek>()int sunday = 6;DayOfWeek day = (DayOfWeek)sunday;

if (weekdays.contains(day)) //isvalid

This is useful because the int to enum cast will cast to an enum even if it doesn’t exist. So its best ot make sure its valid before you continue to use it.

Kudos to the guys in the blog above for working out the code.

Posted in Technology | No Comments »