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?)
.
T : struct
constraint,T?
is ... woolly - it doesn't meanNullable<T>
; it means "T
, but without NRT nulls" - and NRT nulls don't apply for your case, so: it just means:T
– Bertramwhere T : struct
and once withwhere T : class
in order to support both classes and structs? – Roomy(bool, T)
(or aMaybe<T>
, or whatever you want to call it) in all cases - which is essentially likeNullable<T>
, but it works for both classes and structs - then you don't need to differentiate – Bertram