I've come across the following phenomenon and am absolutely bamboozled. I'm using C# 10 with nullables enabled.
default(int?) returns null as expected. The following function, however, returns whatever default(T) is
public static T? ShouldReturnNull<T>()
{
return default(T?);
}
In the case of ShouldReturnNull<int>() we get 0. Shouldn't it also return null?
I have the following code in my program where this becomes an issue:
public T?[] FindKElements(...)
{
var result = new (T, double)?[k];
// ... populate result array,
// possibly including null values...
// return an array containing only the T part or null
return result.Select(e => e is null ? default(T?) : e.Value.Item1).ToArray();
}
Is there a way to keep it this generic but with proper nulls instead when T is a value type? The compiler won't let me use null in place of default(T?).