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

Consider the following code:

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

Incorrect propagation returns T , not Nullable<T> .

How and why?

+5
source share
1 answer

Since the zero propagation path works if the object is on the left side ?. is null, the object on the right side is never executed. Since you know that the right side can never be null, it removes Nullable as a convenience, so you don't need to type .Value every time.

You might 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 it is the behavior that it executes.

+5
source

Source: https://habr.com/ru/post/1259939/


All Articles