Search code examples
c#.netnull

Practical purpose of the null-coalescing assignment operator in C#?


Nulls in C#

One of the new C# features allows us to get rid of nulls in our code with nullable reference types. We are encouraged to add

<Nullable>enable</Nullable>

to the project file due to problems like described here.

Of course, a lot of existing projects don't want to add this. Many, many errors need to be solved when enabling this functionality, so a lot of legacy nulls will still be around. But do we really need additional null-functionality in the language?

The confusion

In the same C# 8.0 release, the null-coalescing assignment operator (??=) has been introduced (see the docs). I understand the behavior, but which problem(s) does it solve for us? Why would we want to assign b to x when it's null x ??= b and have e.g. x = a when it's not null?

The examples I found are very theoretical, can someone give me a real-world application of this operator? Thanks in advance!


Solution

  • A real world example would be lazy loading a backing field on first access when that backing field is null. Something like this:

    private string _dbQuery;
    private string DbQuery => _dbQuery ??= GetQuery(queryName);