Operator Precedence of ??

By Endy Tjahjono. Last update 19 Aug 2013.

This bit me today:

public string stringemup(string a, string b)
{
    var result = a ?? "c" + b ?? "d";
    return result;
}

What do you expect to get when you call stringemup(null, null)? If you say cd then you, like me, forgot that the operator precedence of ?? is very low. It is almost at the bottom of the list.

So the evaluation flow is like this:

  1. a is null, so evaluate "c" + b ?? "d"
  2. "c" + b evaluates to ā€œcā€, so return ā€œcā€

To make the script work as originally intended, I need to add some parentheses:

var result = (a ?? "c") + (b ?? "d");

Extra: did you know that

?null + ""
""
?"" + null
""
?"a" + null + "b"
"ab"
?null + "a" + null + "b"
"ab"

comments powered by Disqus