Posted on June 15th, 2007 by kushal
C# 2.0 introduced a little known, and somewhat useful new operator called the Null Coalescing Operator.
Its like the ternary conditional operator, except less powerful (but admittedly a little neater to look at).
Here’s an example of
coaless coolesc that new feature:
//assuming formValue is of type string string nickName = formValue ?? "Dr. Zoidberg";
… which is the same as this:
string nickName = (formValue == null) ? "Dr. Zoidberg" : formValue;
Its just easiest to think of it as the ‘default’ operator. i.e.
nickName is being set to formValue, but with a default.
Note however, that if you try to change this code:
string nickName = string.IsNullOrEmpty(formValue) ? "Dr. Zoidberg" : formValue;
… to sprinkle some freshly-made coalescing goodness, you could be introducing a subtle bug. (Think empty string)
I’ve never quite understood why people have to come up with the most intimidatory name possible for a simple feature.
Maybe the C# developers wanted to stress similarity with the ANSI SQL function which pretty much does the same thing:
SELECT COALESCE(@nickaname, 'Dr. Zoidberg')
… in which case I can somewhat understand. After all, the SQL guys had to spend their time dealing mostly with simplistic sounding keywords like SELECT, CREATE, UPDATE etc … and some guy probably just snapped. Lawyers have their indictments, plaintiffs, subpoenas and what-not. Doctors regularly get to say words like haemoglobin, pericardium and streptokinase. So someone must have looked up the dictionary and come up a random word.
var nickName = (formValue || "Dr Zoidberg");
var returnValue = (myObject && myObject.myProperty);
…which is called the “Guard” operator apparently. You would use this when you really want to return myObject.myProperty, but you aren’t sure if myObject is null or not, and want to avoid a null pointer error1. Kinda hacky, I know.