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

前端 未结 2 815
心在旅途
心在旅途 2020-12-25 10:34

Now that we have enum constraint, why doesn\'t compiler allow me to write this code?

public static TResult? ToEnum(this String value, TResult?         


        
相关标签:
2条回答
  • 2020-12-25 10:58

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

    public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
    {
    }
    
    0 讨论(0)
  • 2020-12-25 10:59

    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.

    0 讨论(0)
提交回复
热议问题