C Sharp’s Double Question Mark Operator Recipe (??)

riddler

At a recent Microsoft conference, the presenter did some quick programming that raised a gasp of excitement from the audience (I kid you not).  He inserted two question marks in a line of code as if they were an operator and Intellisense did not protest.

“Is that a new language feature in .NET 3.5?”, a member of the audience asked.

The presenter looked somewhat puzzled.  “No, it’s in 2.0.” 

At which point half the audience suddenly realized that this was a secret 2.0 feature they could now use to impress friends and colleagues, while the other half smiled knowingly because they had been using it for over a year.  Such is the way programmers distinguish the wheat from the chaff.

So, if you aren’t using the Null Coalesce Operator, yet, you should.  It is basically a syntactic device for setting a default value for nullable types.  The ?? Operator is the equivalent of the ISNULL function in T-SQL, or the NVL function in PL-SQL, and is very handy when you are trying to translate database values into your business classes.

If, for instance, you have a nullable number type in your Oracle database, or a nullable int in your SQL Server database, it is very convenient to map this to a nullable int in your C# business object.

int? myNum = null;

or

Nullable<Int32> myNum = null;

Being now able to represent this database value, you probably also want to be able to test for the null case and return an alternative value if it turns out to be true.  Here are four ways to do the same thing, in increasingly cool ways, because they are increasingly obscure.

With an IF ELSE block:

if (null == myNum)
    return -1;
else
    return myNum.GetValueOrDefault();

With a SWITCH block:

switch (myNum)
{
   case null:
        return -1;
   default:
        return myNum.GetValueOrDefault();
}

With a Ternary Operator:

return myNum == null ? -1 : myNum.GetValueOrDefault();

And with a Null Coalesce Operator:

return myNum ?? -1;

 

For those who think that in coding compactness == elegance, then this is the syntax for you.  For everyone else, it is a nice recipe you can use to impress co-workers at the next code review.  The most likely, and desirable, response will be:

??

2 thoughts on “C Sharp’s Double Question Mark Operator Recipe (??)

Comments are closed.