Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why T? is not a nullable type?

Tags:

c#

Why the code below doesn't work?

public T? Method<T>() 
{
    /*
     error CS0403: Cannot convert null to type parameter 'T' 
     because it could be a non-nullable value type.
     Consider using 'default(T)' instead.
    */
    return null;
}
like image 563
W.H Avatar asked Mar 11 '26 12:03

W.H


1 Answers

For the sake of backward compatibility, T? is implemented as a pure compile-time construct. For reference type, it's the same as T at runtime. For value type, it is translated to Nullable<T>. The compiler needs to know for sure that T is a value type at compile time to do the translation. Thus for unconstraint type T, the compiler can't assume T? is nullable.

To get the behavior in the OP, the only OOTB way seems to be to overload the method for reference and value types. Unfortunately changing the type constraint is not enough for overload resolution so the name or the parameters would need to be different as well.

public static T? Method<T>() where T : struct
{
    return null;
}

public static T Method<T>(int placeholder = 0) where T : class
{
    return null;
}

Depending on what you're trying to do, Chenga's solutions are likely easier to work with, but this will work if you absolutely need it to return null with a non-nullable type constraint. If you're concerned about default being a non-null value you could also implement an Optional type such as the one in the question linked and return that instead of T.

like image 142
IllusiveBrian Avatar answered Mar 13 '26 02:03

IllusiveBrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!