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.

<span style="color: rgb(43,145,175)"></span>
Order order <span style="color: rgb(255,0,0)">=</span> GetOrder( id ) <span style="color: rgb(255,0,0)">??</span> <span style="color: rgb(0,0,255)">new</span> 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 <span style="color: rgb(255,0,0)">=</span> GetOrder( id );
<span style="color: rgb(0,0,255)">if</span> ( order <span style="color: rgb(255,0,0)">==</span> <span style="color: rgb(0,0,255)">null</span> )
    order <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">new</span> Order();

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

<span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( filename <span style="color: rgb(255,0,0)">!=</span> <span style="color: rgb(0,0,255)">null</span> <span style="color: rgb(255,0,0)">?</span> filename : <span style="color: rgb(163,21,21)">"Filename is undefined"</span> );

You can use the null coalescing operator,

<span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( filename <span style="color: rgb(255,0,0)">??</span> <span style="color: rgb(163,21,21)">"Filename is undefined"</span> );

6 thoughts on “Null Coalescing Operator

Comments are closed.