Null-Coalescing Operator

While at a rather disappointing MSDN event yesterday, I came across one gem of C# 3.0 candy in the form of a null-coalescing operator.  This is basically a short-cut for the oft seen:

string emailAddress = parsedValue != null ? parsedValue : “(Not provided)”;

OR

string emailAddress = String.Empty;
if (parsedValue != null) {
emailAddress = parsedValue;
}
else {
emailAddress = “(Not provided)”;
}

Using the Null-Coalescing Operator
These can now instead be re-written using the new null-coalescing operator as:

string emailAddress = parsedValue ?? “(Not provided)”;

This can roughly be read as “Set emailAddress equal to parsedValue unless it is null, in which case set it to the literal (Not Provided)”.

Applications with Nullable Types
This is also very useful with the new nullable types.  For example, when converting an integer to its value type:

int? recordsAffected = null;
… code that might cause recordsAffected to contain a value …
int totalRecordsAffected += recordsAffected ?? 0;

Here a nullable int type can be added to a regular int without fear of an exception by subsituting 0 in the place of a null value.  It’s always nice to find new candy!

This entry was posted in C# and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *