Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert null to type parameter because it could be a non nullable type when expecting "T?" [duplicate]

Tags:

c#

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.

like image 777
MrD at KookerellaLtd Avatar asked Oct 29 '25 22:10

MrD at KookerellaLtd


1 Answers

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, if T is a string, then T? is a string?.
  • If the type argument for T is a value type, T? references the same value type, T. For example, if T is an int, the T? is also an int.
  • If the type argument for T is a nullable reference type, T? references that same nullable reference type. For example, if T is a string?, then T? is also a string?.
  • If the type argument for T is a nullable value type, T? references that same nullable value type. For example, if T is a int?, then T? is also a int?.

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.

like image 141
Guru Stron Avatar answered Oct 31 '25 15:10

Guru Stron



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!