Reputation: 1885
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?
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!
Upvotes: 8
Views: 4197
Reputation: 5140
The simplest use case is that depending on C# version we previously would have done:
if (number == null)
{
number = someVale;
}
or
number = number ?? someValue;
With the new assignment operator we can shorten it further to:
number ??= someNumber;
A real world example though:
public void WriteErrorToLog(string errorMessage, Exception ex)
{
Log.Warn(errorMessage ??= AppConstants.UnhandledError, ex);
}
Not a perfect real world example. But lets say I want to log soft errors. Writing a template message, with an exception would be much preferable to generating a second error/ exception.
Upvotes: 6
Reputation: 7091
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);
Upvotes: 17