Weird operator precedence with ?? (null coalescing operator)

前端 未结 2 1787
自闭症患者
自闭症患者 2020-12-01 18:26

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 equivale

相关标签:
2条回答
  • 2020-12-01 18:46

    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";
    
    0 讨论(0)
  • 2020-12-01 18:47

    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.

    0 讨论(0)
提交回复
热议问题