Given that it's valid to write
a = b = c = 2;
It would also be nice, rather than
bool allTwo = a == 2 && b == 2 && c == 2;
to instead write
bool allTwo = a == b == c == 2;
But I can't since a == b evaluates to a boolean which can't then be compared to an integer.
Is there a language-design reason it has been implemented this way?
The type of the expression a == b
is boolean, so you would either have to break a rule that an expression means the same thing whatever its context, or have n-ary == operators so that a == b == c
is parsed as (== a b c)
rather than (== (== a b) c)
. Which then means you need to have (a == b) == c
to compare the boolean c to the result of (a == b)
, which is OK, but not the simple C style of grammar which C# is in the tradition of.
Well, the expression c == 2
would return true
, so then b
would be being compared to true
rather than 2.
Edit: It was most likely implemented this way as that's how C-style languages handle boolean expressions. They'd have to make a special exception for multiple terms and implement it differently whereas with the assignment operator it's more straightforward: the right most expression evaluates to a value that can logically be applied to the next expression in the chain. Seems the designers took the simple approach.
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