Monday, 4 May 2020

Question Mark in Programming

If you code in C# or TypeScript you should be aware that different kinds of "?" are showing up more and more often in code bases. As most of these developments are pretty recent I'll try to catch up with them here:

Ternary Operator. For sure this is nothing new, but what I think is becoming more common is to see it used in its nested form. I had always considered these nested cases very confusing, but if you write them in the right way, as explained here they can be pretty expressive and easy to follow.

 (conditionA)
    ? valueA
    : (conditionB)
    ? valueB
    : valueC

Null Coalescing operator "??" This has existed in C# since its first version, but has just been added to TypeScript (and should be featured by JavaScript in the future).

 string city = birthPlace ?? "Paris";

In C#: The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.
In TypeScript it's just the same, only that it applies both to null and undefined (the "nullish" values). Notice that in TypeScript it comes as a replacement for the idiomatic use of "||" to provide default values (with the difference that || applies also to the falsy values: 0, "" and NaN, read more)

Null-coalescing assignment is much related to the above. It has been added to C# 8, but is missing from TypeScript so far.

 city ??= "Paris";
 //is equivalent to this:
 city = city ?? "Paris";

Safe Navigation operator I first saw this operator in Groovy (called Safe Dereferencing there) many years ago and I loved it so much that I wrote about how to try to emulate it at that time in C# and in JavaScript.
C# 6 added this little marvel to our toolbox, and TypeScript has recently added (it should make it into JavaScript in a near future).

 //both in C# and TypeScript 
 var street = person?.Address?.Street;

 //safe array access in C#
 var cityName = cities?[0]?.Name;

 //safe array access in TypeScript
 var cityName = cities?.[0]?.Name;

 //safe Dictionary access in C#
 var cityName = countriesDictionary?["France"];

 //safe property access via indexer in TypeScript
 var cityName = city?.["name"];

 
 //safe delegate invokation in C#
 myFn?.Invoke("a");

 //safe function invokation in TypeScript
 myFn?.("a");

As you can see there are some syntax differences when using it with arrays and with delegates/functions. For C# delegates we have to use ?.Invoke() rather than just ?(). For TypeScript we have to use that odd fn?.(), that likewise we also have to use for array indexes or accessing object properties via indexes (ar?.[0] or obj?.["key"])

No comments:

Post a Comment