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.

Advertisements

Posted on September 29, 2012, in c# and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: