Weird operator precedence with ?? (null coalescing operator)

前端 未结 2 1798
自闭症患者
自闭症患者 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题