The operator ?? in C# (Null coalescing operator)

This operator, introduced in the C# 2.0 specification, is a perfect complement to nullable types by making it easier to handle null values.

One of the typical questions asked by people who are learning .NET with .com is about the ?? operator. This article will put you in the background and explain everything about the “null coalescing operator”, which I had already talked about on other occasions in my blog.

The operator in question, expressed as ?? (two interrogation closures), allows a value to be returned if it is not null, or another alternative value to be returned when the first is null. In other words, code like:

if (s!=null)
return s;
else
return “default”;

Or also written in the form, using the ternary operator:

return (s!=null?s:”default”);

It would be, using the new merge operator, as:

return s ?? “default”;

As you can see, the result is a fairly clean and concise code.

At first glance, it may seem that except for improving readability, it does not provide many advantages compared to the ternary operator “?”, but look at the following code, in a method that returns the name of something whose identifier arrives as a parameter:

string name = getName(id);
if (name==null)
return “Unknown”;
else
return name;

Using the ternary operator ? we could leave it in a single line:

return getName(id)==null?”Unknown”:getName(id);

This has a catch other than readability: if the name is null, we’ll call getName(id) twice, which could have unwanted side effects, or just cause a performance problem. To improve it we could do this, which improves readability and calls the method only once, although it takes longer to code, being very similar to the initial if:

See also  How to convert a PHP associative array to an object

string p = getName(id);
returnp==null? “Unknown” :p;

With the new operator the code would be as simple as this:

return getName(id) ?? “Unknown”;

This is executed in the following way: getName(id) is called and if it is not null, the value obtained is returned. Only if the result of the expression was null would the literal “Unknown” be returned.

As expected, the alternative expression is only evaluated when evaluating the first one has returned a null. In the following code, getAlternate() will only be called when getName() has returned null:

return getName(id) ?? getAlternate(id);

In short, it is a very useful and not too well-known operator that should be taken into account to get a cleaner and more efficient code.

Original post:

Loading Facebook Comments ...
Loading Disqus Comments ...