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'
You can, but you have to add another constraint: the
struct
constraint.Because
System.Enum
is a class, you cannot declare a variable of typeNullable<Enum>
(sinceNullable<T>
is only possible ifT
is astruct
).Thus:
won't compile, and neither will your code.
This is definitely strange (since
Enum
itself is a class, but a specificEnum
that you define in your code is astruct
) if you haven't run into it before, but it is clearly aclass
(not astruct
) as per the docs and the source code.