Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird C# syntax

I've just found this syntax:

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

Of course, being the first time I saw such a syntax, I did not understand it. After debugging, I understood that it 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 legible at all, and it just economizes 3 lines of text?

Edit: my question is about the ? operator, not ??

like image 790
Sean Avatar asked Dec 07 '22 17:12

Sean


2 Answers

That statement doesn't just economize 3 lines, it more readable and also spares a code block, which is important to allow more complex LINQ queries.

What do you think of these two?

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

Opposed to:

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 more than one property?

like image 193
Patrick Hofman Avatar answered Dec 20 '22 13:12

Patrick Hofman


They introduced the ?. operator for the same reason that they introduced the ?? operator: to shorten the code. The same argument you made against ?. could be made against ?? (and to a lesser degree could be made against the ternary operator ? :). But in the end I consider it useful (in the same way that I consider it useful the ternary operator ? :). It is readable if you know what it means. If you don't know what it means any operator is unreadable.

It is useful because the code that you wrote is correct only if date2 is a field/local variable/parameter... If it is a property, there is a guarantee that the property isn't read twice (something that could 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;

so it can get a little more complex than you thought.

like image 37
xanatos Avatar answered Dec 20 '22 12:12

xanatos