Ahh, don't you just love a good ternary abuse? :) Consider the following expression:
true ? true : true ? false : false
For those of you who are now utterly perplexed, I can tell you that this evaluates to true. In other words, it's equivalent to this:
true ? true : (true ? false : false)
But is this reliable? Can I be certain that under some circumstances it won't come to this:
(true ? true : true) ? false : false
Some might say - well, just add parenthesis then or don't use it altogether - after all, it's a well known fact that ternary operators are evil!
Sure they are, but there are some circumstances when they actually make sense. For the curious ones - I'm wring code that compares two objects by a series of properties. It would be pretty nice if I cold write it like this:
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)
Clear and concise. But it does depend on the ternary operator associativity working like in the first case. Parenthesis would just make spaghetti out of it.
So - is this specified anywhere? I couldn't find it.
Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands: If both operands are of the same type, the result is of that type.
Unlike most (all?) other languages, the ternary operator in PHP is left-associative rather than right-associative. The left-associative behavior is generally not useful and confusing for programmers who switch between different languages.
When operator + is said to be left-associative, this means that a + b + c is equivalent to (a + b) + c , as opposed to a + (b + c) . The operator = is right-associative, which means that a = b = c is equivalent to a = (b = c) , as opposed to (a = b) = c . Associativity has nothing to do with the order of evaluation.
Some mathematical operators have inherent associativity. For example, subtraction and division, as used in conventional math notation, are inherently left-associative. Addition and multiplication, by contrast, are both left and right associative. (e.g. (a * b) * c = a * (b * c) ).
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 asa ? b : (c ? d : e)
. end example]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With