Null Coalescing Operator

In C# 2.0, Microsoft introduced the null coalescing operator (??). The ?? operator is a shorthand notation for returning a default value if a reference or Nullable<T> type is null.

The examples below show how the null coalescing operator achieves the same result as traditional conditional statements but with less lines of code. Both sets of examples use property getter methods with assumed fields.

Reference Examples with Conditional Statements

public MyObject MyObjectProperty
{
    get
    {
        if (this.myObject == null)
        {
            return new MyObject();
        }

        return this.myObject;
    }
}

Reference Examples with Null Coalescing Operator

public MyObject MyObjectProperty
{
    get
    {
        return this.myObject ?? new MyObject();
    }
}

Nullable<T> Example with Conditional Statements

public int Number
{
    get
    {
        if (this.nullableNumber.HasValue)
        {
            return this.nullableNumber.Value;
        }

        return 0;
    }
}

Nullable<T> Example with Null Coalescing Operator

public int Number
{
    get { return this.nullableNumber ?? 0; }
}

The main argument against the ?? operator is that developers don’t understand it so it makes the code less readable and maintainable. This is a poor argument in my opinion. As developers, we should never stop trying to improve both ourselves and our teams. This is something that can be taught over lunch one day.

More reading: ?? Operator (C# Reference) – MSDN

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s