Null Coalescing Operator

The first time I saw the ?? operator in C#, I did a double take and had to look it up. The operator, called the null coalescing operator was added in C# 2.0 and is pretty useful, but still fairly unknown.

Order order = GetOrder( id ) ?? new Order();

In the above code, if the return value of GetOrder() is not null, it is assigned to order. If it is null, a new Order is created and assigned. Before the ?? operator, you would have to write something like this;

Order order = GetOrder( id );
if ( order == null )
    order = new Order();

It is also really useful for output. For example, instead of using the conditional operator,

Console.WriteLine( filename != null ? filename : "Filename is undefined" );

You can use the null coalescing operator,

Console.WriteLine( filename ?? "Filename is undefined" );

6 thoughts on “Null Coalescing Operator

Comments are closed.