C# null coalescing operator, ??

C# has a nice ?? operator that can be chained.
In a statement, it will return the first non-null value or null if none are found to not be null.

For example, if you had the code:

string? value1 = null;
string? value2 = nameof(value2);
string? result = value1 != null ? value1 : value2;

The last line could be simplified down to:

string result = value1 ?? value2;

As far as I know, there is no limit on how many ?? can be chained!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s