C# 7.3 Enum constraint: Why can't I use the nullable enum?

C#EnumsRoslynC# 7.3

C# Problem Overview


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'

C# Solutions


Solution 1 - C#

You can, but you have to add another constraint: the struct constraint.

public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
{
}

Solution 2 - C#

Because System.Enum is a class, you cannot declare a variable of type Nullable<Enum> (since Nullable<T> is only possible if T is a struct).

Thus:

Enum? bob = null;

won't compile, and neither will your code.

This is definitely strange (since Enum itself is a class, but a specific Enum that you define in your code is a struct) if you haven't run into it before, but it is clearly a class (not a struct) as per the docs and the source code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKirill KovalenkoView Question on Stackoverflow
Solution 1 - C#Patrick HofmanView Answer on Stackoverflow
Solution 2 - C#mjwillsView Answer on Stackoverflow