The type 'MyObject' must be a non-nullable

2020-08-09 09:50发布

问题:

I'm using .net framework 4.5

I get the following error

Error CS0453 The type 'MyObject' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

  public async Task<Nullable<MyObject>> MyMethod(string myParamter)
    {}

I also tried

  public async Task<MyObject?> MyMethod(string myParamter)
    {}

If I set the thing as nullable then why do I get the red line below the method name with this error message

The stackoverflow answer is easy, make the return type nullable but for me Visual studio doesn't allow it.

回答1:

Since MyObject is an object, and objects are nullable by definition, there is no use to use the Nullable<T> struct or ? operator in order to support null values.

Nullable<T> is for structs (like DateTime) and value types like int, float, etc.



标签: c# generics