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
T
is a reference type,T?
references the corresponding nullable reference type. For example, ifT
is astring
, thenT?
is astring?
.- If the type argument for
T
is a value type,T?
references the same value type,T
. For example, ifT
is anint
, theT?
is also anint
.- If the type argument for
T
is a nullable reference type,T?
references that same nullable reference type. For example, ifT
is astring?
, thenT?
is also astring?
.- If the type argument for
T
is a nullable value type,T?
references that same nullable value type. For example, ifT
is 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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments