17th Aug, 2007

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” );
If you found this post helpful, please "Kick" it so others can find it too:

Responses

[...] Null Coalescing Operator: ?? [...]

Wow.. learn something new every day. Very handy shortcut of which I could make Much use.

Thanks!

Very useful. Definitely slid in under the radar.

[...] != null){ a = b; }else{ a = c; } I was reminded of it again today when I learned it is called the “Null Coalescing Operator”. Javascript has something similar with: a = b || c; I’ve used the hell out of it in [...]

Leave a response

Your response: