22 November 2011

The Null coalescing operator

It seems that a lot of people do not know of the existence of this handy little operator, so I decided to put it up here, so it may help somebody clean up their code.

Have you ever had a Nullable<...> type which you needed to read to a regular value type, but needed a "default" value for when it was NULL, as the regular value type cannot handle it?
Chances are, you've written it in one of the following ways:

int? i = null; // please note that Nullable<int> is the same as int?
int a;
if(i.HasValue) // equal to: if(i != null)
  a = i.Value;
else
  a = -1;

or

int a = i.HasValue ? i.Value : -1; // This is already a bit shorter!

But using the NULL coalescing operator, you can simply write:

int a = i ?? -1;

Which simply means: Read i's value, unless it is NULL, in which case you should use the value -1.
You can also use it in equations, like:
int? a, b, c;
a = null;
b = 2;
c = 1;
int d = (a ?? 1) * ((b ?? 0) + (c ?? 0));

No comments :