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.
1: public static TResult ConvertTo<TResult>( this string source )
2: {
3: if( !typeof(TResult).IsEnum )
4: {
5: throw new NotSupportedException( "TResult must be an Enum" );
6: }
7: return (TResult)Enum.Parse( typeof(TResult), source );
8: }
If the compile time constraint were allowed, I would prefer this
1: public static TResult ConvertTo<TResult>( this string source ) where TResult : Enum
2: {
3: return (TResult)Enum.Parse( typeof(TResult), source );
4: }
The usage is something like this.
1: MyObject.ClosingStatus = input.ConvertTo<ClosingStatus>();
2: //or
3: 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.