A nullable value type value (e.g. int?
) loses its nullability type information when it’s boxed:
Concrete value:
int? valueType = 42;
object? boxed = valueType;
Console.WriteLine(boxed?.GetType()); // System.Int32
Null value:
int? valueType = null;
object? boxed = valueType;
Console.WriteLine(boxed is null); // true
This also means that using Nullable.GetUnderlyingType()
is useless for boxed value types:
public void MyMethod(object? value)
{
if (value is null)
{
return;
}
// Always false!
bool isNullable = Nullable.GetUnderlyingType(value.GetType()) != null;
}