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

  1. Pingback: 22 Links Today (2007-08-20)

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

    Thanks!

  3. Pingback: ItsAllEasy » Blog Archive » Null Coalescing Operator

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>