I have a method with one generic argument, and an optional parameter. The compiler seems to be ignoring the nullability of that type when constructing the default argument. This behavior seems inconsistent with how a default value of local variable is declared with that same type. Why is this?
I would like this to work (use null as the optional parameter) for both reference and value types.
public static void Main()
{
int? @defaultInt = default;
Console.WriteLine(defaultInt is null ? "null" : defaultInt); // null
Do<int>(); // 0, not null
}
public static void Do<U>(U? p = default)
{
Console.WriteLine(p is null ? "null" : p);
}
All you need to do is have 2 overloads with different constraints
public static void Do<U>(U p = default) where U : class
{
Console.WriteLine(p is null ? "null" : p);
}
public static void Do<U>(U? p = default) where U : struct
{
Console.WriteLine(p is null ? "null" : p);
}
Live example: https://dotnetfiddle.net/iOzGDb