I've added some extension methods for strings to make working with some custom enums easier.
public static Enum ToEnum<T>(this string s)
{
return (Enum)Enum.Parse(typeof(T), s);
}
public static bool IsEnum<T>(this string s)
{
return Enum.IsDefined(typeof(T), s);
}
Note -- because of limitations of generic type constraints, I have to write the methods like the above. I would love to use T ToEnum(this string s) where T: Enum to avoid the cast after making the call ... but no can do.
In any event, I figured it would be nice to extend this concept a little bit to return Enum? in those instances where a method signature can accept various nullable enums.
public static Enum? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}
However, this is a no-go due to compiler errors.
error CS0453: The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'
I have to admit I'm a bit confused here as Enum? should be a legitimate return value, no?. I tried something similar, but end up with the same error.
public static T? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (T)Enum.Parse(typeof(T), s) : null);
}
I even decided to rewrite the methods to remove the generics and I get more of the same:
public static bool IsEnum(this string s, Type T)
{
return Enum.IsDefined(T, s);
}
public static Enum? ToEnumSafe(this string s, Type T)
{
return (IsEnum(s, T) ? (Enum)Enum.Parse(T, s) : null);
}
Am I missing something really stupid here?