Home > Back-end >  Why does my && concatenated comparison return different results?
Why does my && concatenated comparison return different results?

Time:06-27

Can somebody explain why the comparison without brackets result1 == true returns a different result than the comparison with brackets result2 == false? Both results should be false because _enum != TestEnum.Member2.

class Program
{
    private static TestEnum _enum = TestEnum.Member1;
    private static int? _int = null;
    private static string _string = null;

    public static void Main(params string[] args)
    {
        var result1 = _enum == TestEnum.Member2 &&
                      _int != null ? _int == 5 : true &&
                      _string != null ? _string == "abc" : true;
        var result2 = (_enum == TestEnum.Member2) &&
                      (_int != null ? _int == 5 : true) &&
                      (_string != null ? _string == "abc" : true);

        Console.WriteLine("result1: "   result1);
        Console.WriteLine("result2: "   result2);
    }
}

public enum TestEnum
{
    Member1,
    Member2
}

.net fiddle: https://dotnetfiddle.net/daA0Lh

CodePudding user response:

The reason is operator precedence

This is the order of precedence for the operators that you're using.

  1. ()
  2. ==
  3. &&
  4. ? :

So...

var result1 = _enum == TestEnum.Member2 &&
                      _int != null ? _int == 5 : true &&
                      _string != null ? _string == "abc" : true;

Is the same as - the parentheses here should not alter the how the expression is evaluated, but should serve to make it clear how the expression is being evaluated.

var result1 = ((_enum == TestEnum.Member2) && _int != null)
       ? (_int == 5)
       : ((true && _string != null)
          ? _string == "abc"
           : true);
  • Related