I added some extension methods for strings to make it easier to work with some custom enums.
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. Due to limitations of general type restrictions, I have to write methods like the ones above. I would like to use T ToEnum (this line is s), where T: Enum, to avoid casting after making a call ... but can't do it.
Anyway, I thought it would be nice to extend this concept a bit to bring back Enum? in cases where the method signature can accept various null enumerations.
public static Enum? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}
However, this is not-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>'
, Enum? , ?. - , .
public static T? ToEnumSafe<T>(this string s)
{
return (IsEnum<T>(s) ? (T)Enum.Parse(typeof(T), s) : null);
}
, :
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);
}
- ?