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

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

    x = cond1 ? result1
      : cond2 ? result2
      : cond3 ? result3
      : defaultResult;
    

    vs

    if (cond1) x = result1;
    else if (cond2) x = result2;
    else if (cond3) x = result3;
    else x = defaultResult;
    

    I like the first one.

    Yes, you can rely on conditional operator associativity. Its in the manual, at the link kindly provided by dcp, stated as "The conditional operator is right-associative", with an example. And, as you suggested and I and others agreed, the fact that you can rely on it allows clearer code.

提交回复
热议问题