What is the operator precedence of C# null-coalesc

2019-01-18 09:54发布

I've just tried the following, the idea being to concatenate the two strings, substituting an empty string for nulls.

string a="Hello";
string b=" World";

-- Debug (amusing that ? is print, doesn't exactly help readability...)

 ? a ?? "" + b ?? "" 

-> "Hello"

Correct is:

? (a??"")+(b??"")
"Hello World"

I was kind of expecting "Hello World", or just "World" if a is null. Obviously this is todo with operator precedence and can be overcome by brackets, is there anywhere that documents the order of precedence for this new operator.

(Realising that I should probably be using stringbuilder or String.Concat)

Thanks.

4条回答
走好不送
2楼-- · 2019-01-18 10:37

Never rely on operator precedence. Always explicitly specify how you want your code to act. Do yourself and others a favour for when you come back to your code.

(a ?? "") + (b ?? "")

This leaves no room for ambiguity. Ambiguity is the breeding ground of bugs.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-18 10:52

It interesting that http://msdn.microsoft.com/en-us/library/6a71f45d.aspx and http://en.csharp-online.net/ECMA-334:_14.2.1_Operator_precedence_and_associativity give different precedence to ??.

msdn:

  1. Conditional
  2. Assignment
  3. Null-coalescing
  4. Lambda

ECMA:

  1. Null Coalescing
  2. Conditional
  3. Assignment

I think the msdn must be wrong, consider:

string a = null;
string b = a ?? "foo";
// What is b now?
查看更多
闹够了就滚
4楼-- · 2019-01-18 10:53

Aside from what you'd like the precedence to be, what it is according to ECMA, what it is according to the MS spec and what csc actually does, I have one bit of advice:

Don't do this.

I think it's much clearer to write:

string c = (a ?? "") + (b ?? "");

Alternatively, given that null in string concatenation ends up just being an empty string anyway, just write:

string c = a + b;

EDIT: Regarding the documented precedence, in both the C# 3.0 spec (Word document) and ECMA-334, addition binds tighter than ??, which binds tighter than assignment. The MSDN link given in another answer is just wrong and bizarre, IMO. There's a change shown on the page made in July 2008 which moved the conditional operator - but apparently incorrectly!

查看更多
Bombasti
5楼-- · 2019-01-18 10:57

The operator precedence is documented on MSDN.

However the precedence on MSDN contradicts the precedence in both the downloadable C# spec also from Microsoft, and the spec on ECMA. Which is a little odd.

Irrespective, as Jon Skeet said in his response, best not to rely on precedence of operators, but to be explicit through use of brackets.

查看更多
登录 后发表回答