Chaining null-coalescing operator

Looking into how the null-coalescing operator can be chained together

Home DailyDrop

Daily Knowledge Drop

The C# null-coalescing operator ?? can be chained together to eventually get to a non-null value.


Null-Coalescing operator

The null-coalescing operator returns the value of its left-hand operand if it isn't null, otherwise it will return the right-hand operand and assign it to the result.

Below is a simple example:

string value1 = "value1";
string? value2 = null;

string resultValue = value2 ?? value1;

Console.WriteLine(resultValue); // "value1" is output 

When the null-coalescing operator (??) is used:

  • The left-hand side value2 will be evaluated and if not null will be assigned to resultValue.
  • If it is null, then the right-hand side value1 will be assigned to resultValue

Chaining

Considering how the operator works (left-hand side evaluated, then right-hand side) - it makes sense that the operator can be chained together:

string value1 = "value1";
string? value2 = null;
string? value3 = null;

string resultValue = value3 ?? (value2 ?? value1);

Console.WriteLine(resultValue);

When the null-coalescing operator is used:

  • The left-hand side value3 will be evaluated and if not null will be assigned to resultValue.
  • If it is null, then the right-hand side will be evaluated:
    • The left-hand side value2 of the right operand will be evaluated and if not null will be assigned to resultValue.
    • If it is null, then the right-hand side value1 will be assigned to resultValue

This can be simplified to no using parenthesis and just using the ?? operator:

string value1 = "value1";
string? value2 = null;
string? value3 = null;
string? value4 = null;
string? value5 = null;
string? value6 = null;

// each value is checked to see if null, and if so the next value is evaluated
string resultValue = value6 ?? value5 ?? value4 ?? value3 ?? value2 ?? value1;

Console.WriteLine(resultValue);

The final value output to the console being value1.


Notes

This is not something I'd thought about, but it makes sense that the operator would work like this, and this would be possible, when you consider how the values are evaluated. It is a small simple, technique to use to simplify and reduce unnecessary code.


References

Chaining the C# ?? Operator

Daily Drop 55: 19-04-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net operator coalescing