series0ne series0ne - 22 days ago 5
C# Question

Why does null-propagation of Nullable<T> return T and not Nullable<T>?

Consider the following code:

Nullable<DateTime> dt;

dt. <-- Nullable<DateTime>
dt?. <-- DateTime


Null propagation returns
T
, rather than
Nullable<T>
.

How and why?

Answer

Because the way null propagation works if the object on the left hand side of the ?. is null the object on the right hand side is never executed. Because you know the right hand side can never be null it strips off the Nullable as a convince so you don't need to type .Value every time.

You could think of it as

public static T operator ?.(Nullable<U> lhs, Func<U,T> rhs) 
    where T: class
    where U: struct
{
    if(lhs.HasValue)
    {
        return rhs(lhs.Value);
    }
    else 
    {
        return default(T);
    }
}

The above code is not legal C#, but that is the behavior it does.