I have type with one generic type argument, that contains a method with and an optional parameter. The code treats the nullability of that type in an unexpected way when constructing the default argument.
This is closely related to Nullable default parameter with generic type where a good solution for a function was given.
In the case of a class however, is there a way to write this without creating two copies of the same class, one with a value type constraint, and other handling reference types?
Thanks!
public static void Main()
{
int? @defaultInt = default;
Console.WriteLine(defaultInt is null ? "null" : defaultInt); // null!
Test<int> t = new();
t.Do(); // 0! not null
Test<object> o = new();
o.Do(); // null
TestS<int> ts = new();
ts.Do(); // null
}
public class Test<T>
{
public void Do(T? p = default)
{
Console.WriteLine(p is null ? "null" : p);
}
}
public class TestS<T> where T : struct
{
public void Do(T? p = default)
{
Console.WriteLine(p is null ? "null" : p);
}
}