Null-coalescing operator and associativity

Chaining the null-coalescing operators together

Home DailyDrop

Daily Knowledge Drop

The null-coalescing operator (??) is right-associative, and can be chained together to check multiple values, in order, to eventually arrive at a non-null value.


Example

The example for this situation is fairly simple - the operator ?? can be used in a chain to check (and return) the first non-null value:

int? GetValue(int? value1, int? value2, int? value3, int defaultValue)
{
  // chain the operator and return the first non-null value
    return value1 ?? value2 ?? value3 ?? defaultValue;
}

The values are evaluated left to right to check if they are null, and the first non-null value is returned. In this example defaultValue is an int and as such cannot be null, so the method will always return a value.

Invoking this with a variety of permutations:

Console.WriteLine(GetValue(null, null, 0, 0));
Console.WriteLine(GetValue(null, 1, 2, 0));
Console.WriteLine(GetValue(2, 5, null, 0));

Results in the following, expected output:

0
1
2

Each each case the first non-null value is returned. If all nullable values are null, then the default is returned.


Notes

This small, but useful piece of information for today might seem obvious, and it is once you think about it - personally I've just never encountered the technique or the need to chain together multiple null checks using the null-coalescing operator. However, if I ever do, I now know that chaining is possible.


References

Null-Coalescing Operators’ Associativity

Daily Drop 211: 28-11-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 nullcoalescing associativity