Ternary operator associativity in C# - can I rely on it?

前端 未结 5 680
旧时难觅i
旧时难觅i 2020-12-31 02:37

Ahh, don\'t you just love a good ternary abuse? :) Consider the following expression:

true ? true : true ? false : false

For those of you w

5条回答
  •  一生所求
    2020-12-31 03:29

    The assertion that parentheses detract from the readability of the code is a false assumption. I find the parenthetical expression much more clear. Personally, I would use the parentheses and/or reformat over several lines to improve readability. Reformatting over several lines and using indenting can even obviate the need for parentheses. And, yes, you can rely on the fact that the order of association is deterministic, right to left. This allows the expression to evaluate left to right in the expected fashion.

    obj1.Prop1 != obj2.Prop1
         ? obj1.Prop1.CompareTo(obj2.Prop1)
         : obj1.Prop2 != obj2.Prop2
               ? obj1.Prop2.CompareTo(obj2.Prop2)
               : obj1.Prop3 != obj2.Prop3
                      ? obj1.Prop3.CompareTo(obj2.Prop3)
                      : obj1.Prop4.CompareTo(obj2.Prop4);
    

提交回复
热议问题