series0ne series0ne - 1 year ago 66
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
, rather than

How and why?

Answer Source

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
        return rhs(lhs.Value);
        return default(T);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download