The Null Coalescing Operator (Or how to make Default values sound frightening)

Posted on June 15th, 2007 by kushal

C#

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)

SQL

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.

Javascript

Interestingly enough, even though this feature isn’t supported by Java (as of Java 5), Javascript has long supported this. Of course Javascript really has nothing to do with Java. But its hard not to form an association in one’s head.
Anyway, here’s the equivalent in Javascript:

var nickName = (formValue || "Dr Zoidberg");

While on the topic of Javascript and null coalescence, beware though. Don’t get confused with this Javascript statement:

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.

If you’re wondering how come all this doesn’t conflict with Javacript’s implementation of the logical OR and AND operators, its because they dont necessarily return booleans and Javascript evaluates all objects, non-empty strings and non-zero numbers to true. So both the “guard” and “default” operators are really Javascript’s own peculiar implementation of logical AND and OR operators.
Javascript often strikes me as the Ferris Bueller of programming languages. Not always taken seriously, but still surprisingly inventive and most of all – very, very annoying.

1: The specific error message varies from browser to browser. In IE this would show up as “myProperty is null or not an object”, in Mozilla based browsers the error message would be “myObject has no properties” (which makes a little more sense, no?)

6 Responses

  1. Matt Says:

    I honestly find this operator rarely useful. I typically want something like this:

    string myString = myObject.Value ?? “default value”;

    as in, I want whatever Value is, as long as myObject is not null, otherwise the default value. Which obviously ?? does not accomplish, but I just find this scenario comes up more often.

    have to stick with the old standby…
    string myString = myObject == null ? “default value” : myObject.Value;

  2. From the “Couldn’t have said it better myself” department « Tim.GetInstance( ) Says:

    […] From the “Couldn’t have said it better myself” department “Javascript often strikes me as the Ferris Bueller of programming languages. Not always taken seriously, but still surprisingly inventive and most of all – very, very annoying.” -kushal […]

  3. kushal Says:

    Hi Matt,
    Yes that feature might come in useful alright. Although I think there may be a little more it. For example

    myString = myObject.myValue 
             [?? or some other GuardOperator Here] "Default Value";

    … is straight forward enough. But what if someone were to write this:

    myString = myObject.mySubObject.myValue 
               [GuardOperator Here] "Default Value";

    Now should the compiler set the default value only if mySubObject is null? (and throw an exception if myObject is null). Or should it guard against the entire expression altogether?

    Because it isn’t really useful if doesn’t guard against the entire expression, I guess what you’re really asking for is a shortcut for catching NullReferenceExcptions as opposed to a shortcut for an if-else clause. Something like this:

    string myString;
    try
    {
    	myString = myObject.mySubObject1.mySubObject2.Value;
    }
    catch(NullReferenceException e)
    {
    	myString = "Default Value";
    }

    … and I agree that would indeed be useful. (The Javascript guard operator is a little odd because it can return either myValue or myObject.)
    Its a pity one can’t really write a method for doing this. (In C# that is) You can use reflection but then you’d lose the strong typing.

  4. kushal Says:

    Glad that struck a chord Tim :)

  5. Jonathan Allen Says:

    Completely useless for me. The only time this would be helpful for me is when I’m cleaning database nulls but it doesn’t support them nor does it support value types.

  6. kushal Says:

    It actually does support value types. You only have to use Nullable Types (just add a question mark at the end and they are nullable).
    As for handling null values in a database, I would have suggested you use System.Data.SQLTypes, but MS seems to suggest that we use the IsNull property of the INullable interface instead. (all the SQLTypes implement it)

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Posted in C#, Javascript | 6 Comments »

Archives

Categories

Blogroll