Tip of the day: Double question mark

A not so common, but very usefull operator is the double question mark operator (??). This can be very usefull while working with nullable types.

Lets say you have two nullable int:

int? numOne = null;
int? numTwo = 23;

Scenario: If numOne has a value, you want it, if not you want the value from numTwo, and if both are null you want the number ten (10).

Old solution:

if (numOne != null)
    return numOne;
if (numTwo != null)
    return numTwo;

return 10;

 Or another solution with a single question mark:

return (numOne != null ? numOne : (numTwo != null ? numTwo : 10));

But with the double question mark operator we can do this:

return ((numOne ?? numTwo) ?? 10);

As you can see, the double question mark operator returns the first value that is not null.

10 Comments

  • for those that are interested this operator is named the coalesce operator

  • Yes this is handy, it shortens the code...but riddle me this...is it more readable?
    The answer from here is: No.
    Why is readability important?

    if (numOne != null)
    return numOne;
    if (numTwo != null)
    return numTwo;

    Can without much problem be translated into VB, Pascal, C++....or understood. A language if it branches out too far into its own dialect becomes harder to understand and translate.

    This doesn't add any new useability to the language so then what's the point? Its just a dialect change.

  • Hum, how come this can't be found at msdn.com...?

  • I guess you can find it somewhere, it´s a really good operator.

  • Thanks for information :)

  • >> This doesn't add any new useability to the language

    Well, actaully it does in this sense ...

    If you need a value in one statement, such as when determining what to pass to a base class (which is where I came across this syntax)

    example:

    public MyClass(IEnumerable items) : base(items ?? new T[] {})...

  • this is interesting. i didnt know this
    thanks dude

  • I once wrote an XSL script to parse XML and make decisions on where to channel the resulting xml in the XSL. It was very clear to someone who could read xsl. In the following release an older developer turned this into 2 screens of if statements as he said it was "easier to follow".

    Keep up or get out of the way I say.

  • Tip of the day double question mark.. Bang-up :)

  • Indeed it's there for a very long period of time .
    now i realize i could use this in my code

    >>my earlier code
    objbulk.DIFFERENCEVALUE = (dr[9].ToString() != null) ? Convert.ToDecimal(dr[9].ToString()) : 0;

    >>>with ??Operator i can simply
    objbulk.DIFFERENCEVALUE = Convert.ToDecimal(dr[9].ToString()) ?? 0;

    awesome ShortHand technique.

Comments have been disabled for this content.