Weird C # syntax

I just found this syntax:

date1 = date2?.ToString("yyyy-MM-dd") ?? date3;

      

Of course, the first time I saw this syntax, I didn't get it. After debugging, I realized that this is equivalent to:

if(date2 != null)
   date1 = date2.ToString("yyyy-MM-dd");
else
   date1 = date3;

      

My question is, why was this syntax introduced since it is not readable at all and it just saves 3 lines of text?

Edit: my question is about? operator, not?

+3


source to share


3 answers


This statement not only saves 3 lines, it is more readable, it also reserves a block of code, which is important for enabling complex LINQ queries.

What do you think of these two?

var x = collection.Select(x => new SomeClass(x?.Property ?? "default"));

      



Against:

var x = collection.Select(x => 
                               {
                                   string value = null;
                                   if (x != null)
                                   {
                                       value = x.Property;
                                   }

                                   if (value == null)
                                   {
                                       value = "default";
                                   }

                                   return new SomeClass(value);
                               }
                         );

      

The first is much more expressive and powerful. And what if you have multiple properties?

+11


source


They introduced the operator ?.

for the same reason they introduced the operator ??

: to shorten the code. The same argument you made against ?.

can be made against ??

(and to a lesser extent could be made against the ternary operator ? :

). But in the end I find it useful (just as I find the tronical operator useful ? :

). It's readable if you know what it means. If you don't know what it means that any operator is unreadable.

This is useful because the code you wrote is only correct if it date2

is a field / local variable / parameter ... If it is a property, there is a guarantee that the property is not read twice (something that can be quite important, depending on how the parameter is calculated). The code is changed to something like:



DateTime? temp = date2;
string date1 = temp != null ? temp.GetValueOrDefault().ToString("yyyy-MM-dd") : date3;

      

therefore, it might get a little more complicated than you thought.

+2


source


This type of syntax was recently added with C # 6.0. ?.

called null-conditional . This Microsoft article describes all the new features in C # 6.0, as well as a list of this new null-conditional operator .

+1


source







All Articles