-1

After a incomprehensible bug, I found a strange behavior of && operator.

I extracted my code:

string s = "123";
Console.WriteLine(false && s.Length < 2 ? true : s.Substring(0,2).ToUpper() != "GA");

I expected the result is false, but it gives me true

To receive the expected result, I put the second statement in ()

Console.WriteLine(false && (s.Length<2 ? true : s.Substring(0,2).ToUpper() != "GA"));

It gives me false

Code tested in fiddle

Someone has passed in same situation ?

Trevor
  • 7,777
  • 6
  • 31
  • 50
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • It's not strange behavior nor a bug... it's correct as per precedence and order of evaluation. [See](https://stackoverflow.com/questions/1196703/c-sharp-conditional-and-or-precedence) that or [this](https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019). Specifically there's this `Operators are listed in descending order of precedence`, please read. – Trevor Nov 07 '19 at 15:03
  • 5
    [Operator precedence](https://learn.microsoft.com/dotnet/csharp/language-reference/operators/). `&&` has higher precedence than `? :`. The first is interpreted as `(false && s.Length < 2) ? x : y`, so `s.Substring(0,2).ToUpper != "GA"` is evaluated, which is `true`. – Jeroen Mostert Nov 07 '19 at 15:03
  • Possible duplicate of [C# conditional AND (&&) OR (||) precedence](https://stackoverflow.com/questions/1196703/c-sharp-conditional-and-or-precedence) – Trevor Nov 07 '19 at 15:05

2 Answers2

4

This behaviour is correct. Let's see:

string s = "123";
Console.WriteLine(false && s.Length < 2 ? true : s.Substring(0,2).ToUpper() != "GA");

The expression for the ternary expression is: false && s.Length < 2 // s.Length is 3 => 3 < 2 == false

Therefore the expression s.Substring(0,2).ToUpper() != "GA" is executed and returns true, as "12" != "GA".

Thomas Voß
  • 1,145
  • 8
  • 20
  • 1
    This is a *decent* answer, but I think can be improved by adding, *why precedence matters and order of evaluation*... – Trevor Nov 07 '19 at 15:10
  • @Çöđěxěŕ: True, I found an article here: https://stackoverflow.com/questions/5473107/operator-precedence-vs-order-of-evaluation – Thomas Voß Nov 07 '19 at 15:22
1

It was evaluated as (false && s.Length < 2) ? true : s.Substring(0,2).ToUpper() != "GA", in which the conditional is false, so ends up as s.Substring(0,2).ToUpper() != "GA", which is true.

Worth noting that if the precedence was as you wanted/expected it to be, the result would always be false. Due to short-circuiting, the ternary conditional would never even be executed.

JAD
  • 2,035
  • 4
  • 21
  • 35