Ramblings from the Creator of WilsonDotNet.com
To further constrain the input for T, add a type constraint of where T: struct. You can't use : enum, so struct is the next best thing.
Another handy utility enum function I use quite often:
public static T ParseEnum<T>(string value) where T: struct
{
return (T)Enum.Parse(typeof(T), value, true);
}
I've been looking at the implementation of Enum.ToObject(Type, int) (using Lut'z Reflector, of course), but can't seem to think of a reason to use it. Why not cast the int directly to it's enum?
MyEnum = (MyEnum)typeValue;
Can you demo the usage?
As for the usage, consider an enum named MyEnum and a variable of that enum type that you want to load from an int value, possibly one you've stored in the database -- just do the following:
MyEnum test = ToEnum<MyEnum>(value);
As for the direct cast, that's a good question, and I could have sworn I'd tried that many times and it didn't work -- although it did just now in my test. Maybe I'm thinking of a limitation I encountered in .net v1 that I've been working around -- but maybe I'm wrong there as I didn't retest that assumption. Oh well, it seems that its not necessary for .net v2 at any rate, and if you have generics then you have .net v2, so mute point I suppose.
Thanks for the comments.
I would throw something like this into your helper:
System.Diagnostics.Debug.Assert(typeof(T).IsEnum);
all these helper function can not ensure valid value of enum.
at .net 2.0,
support MyEnum only have two enum value, and the value is 10, no exception will throw. So i don't know MyEnum test now have a invalid value.
You can call Enum.IsDefined in the helper function first to guarantee a valid value, and if it fails then throw an exception. The same problem occurs with the simple cast syntax, so at least using a helper function makes it easier to add extra things like this when you find it is needed.
Be careful about the performance of enum operations.