The C# ‘??’ Null-Coalescing Operator. It’s actually simple and really useful.

Category: .NET C# Tags: ,
March 11, 2015

Many programmers have not heard of the ?? operator in C# but it is one of the most useful operators. It’s all to do with easing the pain of dealing with nulls. The official Microsoft definition is:

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

A simple example is (say) an integer defined as a nullable type:

int? x = null;

You then define a normal integer:

int y;

You know the problem when you do y = x. You start to need casts or conversions and there’s a danger of run-time errors. The ?? operator solves this problem easily:

y = x ?? 0;

So y is set to x when x is an integer, but if x is null y is set to 0.

It is useful with strings too:

WriteLine( someName ?? “Name not given” );

I use them in getters, example:

get { return (ViewState[“template”] ?? “”).ToString(); }

It makes life a little easier.

P.S. If you are wondering what the definition of ‘coalescing’ is, then it means ‘combining’, or ‘bringing together’.