Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if T is ‘int’, then I want the answer to be null, not 0.

>Solution :

Because T is unconstrained in your case, and for unconstrained (neither to struct nor to class) generic type parameters TT? 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading