Now that we have enum constraint, why doesn't compiler allow me to write this code?
public static TResult? ToEnum<TResult>(this String value, TResult? defaultValue)
where TResult : Enum
{
return String.IsNullOrEmpty(value) ? defaultValue : (TResult?)Enum.Parse(typeof(TResult), value);
}
The compiler says:
Error CS0453 The type 'TResult' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'
System.Enumis a special class(which can't be used as type parameter constraint anyway). It is so special that it inherits fromSystem.ValueTypebut is a reference type. stackoverflow.com/questions/14561338/…Enumbase class is a weird case in the .NET type hierarchy, and all classes that inherit from it are value types. I thought the new constraint was akin to theclassorstructconstraints, not just allowing a base class constraint that was forbidden before.