Monthly Archives: September 2012

The C# Null Coalesce Operator

This post was written partly as a reminder to myself that the C# null coalesce operator exists and can be used effectively to write concise readable code. But what is it?

The Null Coalesce operator in C# is a shorthand way of returning a value but specifying a default if that value is null. This is easily demonstrated using a quick example.

String text = "Hello";
String greeting = text ?? "The greeting was null";

In this case, greeting is assigned the value of text unless text is null. In that case it is given a default value of “The greeting was null”. Clearly this could be achieved by other means such as an if..else statement or a ternary operator, however this method provides a very terse syntax. In addition it deals well with results of direct method calls. For example:

String value = MyFunction() ?? "No value returned";

is much better than

String value2 = MyFunction() != null ? MyFunction() : "No value returned";

and more efficient too as the function is only called once.

It should be noted though that it only deals with nulls and understandably does not handle empty strings. For this the String.IsNullOrEmpty can be used instead.