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.

This C# article examines the null coalescing operator. An example program shows the syntax.

Example

The null coalescing operator is useful inside properties. Often, a property that returns an object (such as a string) may be null. However, it is sometimes clearer to have code inside the property that handles null values and returns a custom value in that case. With the ?? operator, we can do this simply.

Program that uses null coalescing operator [C#]

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
Null keyword

Explanation. 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". Thus, you can always use an expression like Name.Length, because Name will never return null. A NullReferenceException will never be thrown.

NullReferenceException and Null Parameter

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.

Nullable Int Nullable Bool Nullable DateTime

Summary

The C# programming language

We saw an example of the null coalescing operator in the C# language. With this operator, you can handle null references with less source code. The null coalescing operator is very similar to the ternary operator: it is shorter but less flexible.

Ternary Operator Use If Statement
.NET