this code complains
public static T? Foo<T>()
{
return null;
}
with
Error CS0403
Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
But aren't I telling the compiler it can be null?
If T is int, then I want the answer to be null, not 0.
Because T is unconstrained in your case, and for unconstrained (neither to struct nor to class) generic type parameters T - T? is handled differently for value types and reference types. From the docs:
- If the type argument for
Tis a reference type,T?references the corresponding nullable reference type. For example, ifTis astring, thenT?is astring?.- If the type argument for
Tis a value type,T?references the same value type,T. For example, ifTis anint, theT?is also anint.- If the type argument for
Tis a nullable reference type,T?references that same nullable reference type. For example, ifTis astring?, thenT?is also astring?.- If the type argument for
Tis a nullable value type,T?references that same nullable value type. For example, ifTis aint?, thenT?is also aint?.
So for Foo<int> actual signature will be int Foo<int>, hence the error.
If it is suitable for you - constrain T to be either struct or class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With