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

前端 未结 5 711
旧时难觅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:19

    Yes, you can rely on this (not only in C# but in all (that I know) other languages (except PHP … go figure) with a conditional operator) and your use-case is actually a pretty common practice although some people abhor it.

    The relevant section in ECMA-334 (the C# standard) is 14.13 §3:

    The conditional operator is right-associative, meaning that operations are grouped from right to left. [Example: An expression of the form a ? b : c ? d : e is evaluated as a ? b : (c ? d : e). end example]

提交回复
热议问题