Technical Journal

Programming, software technologies, operating systems, IT

Enum to List

I’ve found this method useful lately so I thought I should add it here where everyone can see it.
It is meant to be used with the .NET Compact Framework. In the full framework this would have been much easier -
without reflection.
What the method does is that it adds the enum’s fields to a generic list of the same type T as the enum.

public static List EnumToList( )
{
Type enumType = typeof( T );

if( enumType.BaseType != typeof( Enum ) )
{
throw new ArgumentException( “Not an enum type!” );
}

List enumFieldList = new List( );

FieldInfo[ ] enumFields = typeof( T ).GetFields( );

foreach( FieldInfo fieldInfo in enumFields )
{
if( !fieldInfo.IsSpecialName )
{
enumFieldList.Add( (T) Enum.Parse( enumType, fieldInfo.Name, false ) );
}
}

return enumFieldList;
}

April 24, 2009 - Posted by andocs | Windows CE | , , , , | No Comments Yet

No comments yet.

Leave a comment