sobota 4. dubna 2020

Null-Conditional Operator is Short Circuiting in C#

In C#, similar to boolean operators, the null-conditional operator (?.) is short circuiting. This allows us to simplify longer chains of member access operations. In this article I will explain what that means.

Documentation

According to documentation:

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.
See:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators

Example

Let me illustrate this with a (contrived) example. Say we have a page in a document which might or might not have a header. A header has a couple of properties, such as text, padding, etc.

We can represent this scenario using the following classes:

class Page
{
  // nullable
  public Header Header { get; set; }
}

class Header
{
  public int Padding { get; set; }
  public string Text { get; set; }
}

Suppose we want to calculate the length of header text. Since the Header property can be null, we need to use the null-conditional operator when accessing the Text member.

var length = page.Header?.Text.Length ?? 0;

If you are like me, you thing about the ?. operator as if it works in the following manner.

x?.y <=> x == null ? null : x.y

There is one catch, though. If we follow this evaluation rule in our example

page.Header?.Text => null

we should expect NullReferenceException on the next member access.

null.Length

This is where the short circuiting property comes useful. When the ?. operator evaluates to null, the rest of the expression is skipped and the whole expression evaluates null.

page.Header?.Text.Length => null

No need to protect the next member access with another null-conditional operator.

0 komentářů:

Okomentovat