TheDeveloperBlog.com


C# Null Coalescing Operator

Null coalescing operator. The null coalescing operator uses two question marks. With it you can use a custom value for a null reference variable. The operator, specified with the "??" characters, has shorter source code and is equivalent to testing for null.


Example. The null coalescing operator is useful inside properties. Often, a property that returns an object (such as a string) may be null. This null value complicates certain programming constructs.

Null

It is sometimes clearer to have code inside the property that handles null values and returns a custom value in that case. This is simple to do with the "??" operator. This example demonstrates a null coalescing property.

C# program that uses null coalescing operator

using System;

class Program
{
    static string _name;

    /// <summary>
    /// Property with custom value when null.
    /// </summary>
    static string Name
    {
	get
	{
	    return _name ?? "Default";
	}
	set
	{
	    _name = value;
	}
    }

    static void Main()
    {
	Console.WriteLine(Name);
	Name = "Perls";
	Console.WriteLine(Name);
	Name = null;
	Console.WriteLine(Name);
    }
}

Output

Default
Perls
Default

The Name property on the Main type will never return a null string. If the backing store (_name) to the property is null, it will return the string "Default". Calling code does not need to check against null.

And: You can always use an expression like Name.Length, because Name will never return null. NullReferenceException is never thrown.

NullReferenceException

Value types. You cannot use the null coalescing operator on value types such as int or char. However, if you use nullable value types, such as "int?" or "char?" you can use the "??" operator. A nullable type is a struct that can be null.

Nullable IntNullable BoolNullable DateTime

Summary. We used the null coalescing operator. With this operator, you can handle null references with less source code. The null coalescing operator is similar to the ternary operator. It is shorter but less flexible.

Ternary Operator