Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 945
Matthew Layton Avatar asked Nov 17 '16 22:11

Matthew Layton


1 Answers

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 convenience 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.

like image 194
Scott Chamberlain Avatar answered Oct 17 '22 03:10

Scott Chamberlain