Null-coalescing Operator

Posted written by Paul Seal on October 02, 2015 C#

Shorter code for using the value of a nullable object or another value if not.
When using nullable types, you need to check for null before using the value. The most basic way of doing this would be to check it in an if statement like this:

int newValue;

if(nullableVariable.HasValue)
{
    newValue = nullableVariable.Value;
}
else
{
    newValue = 0;
}

You could of course shorten it to be like this:

if(nullableVariable.HasValue)
    newValue = nullableVariable.Value;
else
    newValue = 0;

And to go even further, which is the way I would normally do it is:

int newValue = nullableVariable.HasValue ? nullableVariable.Value : 0;

there is an even shorter way, which uses the null-coalescing operator:

int newValue = nullableVariable ?? 0;

It's as simple as:

If the left variable has a value then use it, otherwise use the value on the right.