Weird operator precedence with ?? (null coalescing operator)

无人久伴 提交于 2019-11-26 17:47:53

问题


Recently I had a weird bug where I was concatenating a string with an int? and then adding another string after that.

My code was basically the equivalent of this:

int? x=10;
string s = "foo" + x ?? 0 + "bar";

Amazingly enough this will run and compile without warnings or incompatible type errors, as will this:

int? x=10;
string s = "foo" + x ?? "0" + "bar";

And then this results in an unexpected type incompatibility error:

int? x=10;
string s = "foo" + x ?? 0 + 12;

As will this simpler example:

int? x=10;
string s = "foo" + x ?? 0;

Can someone explain how this works to me?


回答1:


The null coalescing operator has very low precedence so your code is being interpreted as:

int? x = 10;
string s = ("foo" + x) ?? (0 + "bar");

In this example both expressions are strings so it compiles, but doesn't do what you want. In your next example the left side of the ?? operator is a string, but the right hand side is an integer so it doesn't compile:

int? x = 10;
string s = ("foo" + x) ?? (0 + 12);
// Error: Operator '??' cannot be applied to operands of type 'string' and 'int'

The solution of course is to add parentheses:

int? x = 10;
string s = "foo" + (x ?? 0) + "bar";



回答2:


The ?? operator has lower precedence than the + operator, so your expression really works as:

string s = ("foo" + x) ?? (0 + "bar");

First the string "foo" and the string value of x are concatenated, and if that would be null (which it can't be), the string value of 0 and the string "bar" are concatenated.



来源:https://stackoverflow.com/questions/3259352/weird-operator-precedence-with-null-coalescing-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!