This program has two errors:
using System;
T? f<T>(T? t)
{
t = null; // Error CS0403 Cannot convert null to type parameter 'T' because it could be a non-nullable value type
return default(T?);
}
if(f(10) is null) // Error CS0037 Cannot convert null to 'int' because it is a non-nullable value type
Console.WriteLine("null");
T?
has to be a nullable type. But it seems T?
is the same as T
in the above program.
Is ?
ignored in T?
?
Edit: Both errors disappear with a struct
constraint:
using System;
T? f<T>(T? t) where T : struct
{
t = null; // error
return default(T?);
}
if(f<int>(10) is null) // error
Console.WriteLine("null");
I don't understand why the constraint changes the results.
T?
means just "defaultable". But then,int
(which is defaultable,default(int)=0
) would beint?
, which is obviously not true. Can you be more specific regarding "in C#,T?
doesn't always mean nullable"? Do you have an example forT
whereT?
can NOT be null? – Issie