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's. Check 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.