The coalesce operator, BKA the double question marks

13 January, 2009 § 4 Comments

In C#, there is a nice little operator that is rarely used. I’m not sure if this is because most people haven’t heard of it before or they just don’t know how to use it.

Basically, this operator allows you to check if an object is null, and if it is, return a different object.

Use this:

return userName ?? string.Empty;

Instead of this:

return (userName != null) ? userName : string.Empty;

Pretty simple, and it will save some typing. I’ve heard arguments against using the ternary operator from people claiming not to use it because fellow developers wouldn’t know what it is. That’s not the mindset we should have. If an operator exists in a language and there is a perfectly valid use for it, then go ahead and use it. When your colleage sees it, they will learn something about the language they never knew before and will most likely appreciate it.

Tagged: , ,

§ 4 Responses to The coalesce operator, BKA the double question marks

  • A.J. says:

    In c++ we have something similar. Given ‘a’ can be evaluated to true or false; instead of writing:

    return a ? a : b;

    we could write:

    return a ? : b;

    Only it doesn’t compile in Visual c++😦 So ‘a’ could be an int; but it wouldn’t work if ‘a’ was a string/CString.

  • msujaws says:

    That’s pretty cool to see. I’ve never seen that operator before. Is it a special implementation of the ternary operator?

  • Raymond Li says:

    I find the ternary operator is avoided, because it looks a bit cryptic. Probably the same with this null-coalesce operator. However, it probably has a good place with regard to readability when you start chaining the operator:

    x = nullableVal1
    ?? nullableVal2
    ?? nullableVal3
    ?? lastResortVal;

  • Jared says:

    @Raymond: While any operator can look cryptic if it is overused or used awkwardly, operators like ternary and coalesce offer concise and quick to read lines of code by reducing the signal to noise ratio. Hopefully this would translate to less bugs in the code because they are easier to spot.

    I also like to take the stance that if an operator like ternary is not well known, then using it is the perfect opportunity to start up a conversation with coworkers about its benefits and uses. If we are too scared to innovate and use different technologies we will continue to be writing 1980’s C++ in 2020.

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

What’s this?

You are currently reading The coalesce operator, BKA the double question marks at JAWS.

meta