It seems that enums might be the neglected step-child when it comes to Generics and Extensions.  I've tried defining generics that are constrained to enums.  No luck.  I faced much frustration trying to get my generic methods to work.  I finally came up with a method that meets my need.  But, I had to add a little bit of run-time type checking.

Instead of repeating Enum.Parse throughout my code, I wanted to create a simple generic extension method that would do it for me.

I just discovered that my extension is practically identical to Kirill Osenkov'sCheck out his discussion here.
public static TResult ConvertTo<TResult>( this string source )
{
if( !typeof( TResult ).IsEnum )
{
throw new NotSupportedException( "TResult must be an Enum" );
}
return (TResult)Enum.Parse( typeof( TResult ), source );
}
If the compile time constraint were allowed, I would prefer this
public static TResult ConvertTo<TResult>( this string source ) where TResult : Enum
{
return (TResult)Enum.Parse( typeof( TResult ), source );
}
The usage is something like this.
MyObject.ClosingStatus = input.ConvertTo<ClosingStatus>();
//or
reader.GetString( 2 ).ConvertTo<ClosingStatus>();
After I came up with this, I searched to find out if anyone else out there found a better way to resolve the limitations surrounding enums.  I found Christopher Bennage's post on Enum<T> and I like it quite a bit.
posted on Saturday, June 28, 2008 11:10 PM
Filed Under [ .Net Design ]

Comments

Gravatar
# re: C# Generics for Enums
on 6/29/2008 10:53 PM
I'm glad you liked it, and I am in complete agreement about being able to constrain generics to enums. :-)
Your Comment




 
Please add 8 and 8 and type the answer here: