What is the operator precedence of C# null-coalescing (??) operator?

前端 未结 4 1079
难免孤独
难免孤独 2020-12-05 18: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\         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 19:12

    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!

提交回复
热议问题