Search code examples
c#and-operator

And operator behaves odd


I have two variable spn and fmi.

(3064,11),(3064,14),(3064,16),(123,11)

spn gets the first values(3064,3064,3064,123) and fmi gets (11,14,16,11)

and here is the code :

    if ((Spn != 3064) && (Fmi != 11) || (Fmi != 16))
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   Added", Spn, Fmi);
    }
    else
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   skipped", Spn, Fmi);
    }

So I want the output to show :

(3064,14) added
(123,11) added
(3064,16) skipped
(3064,11) skipped

the above code is wrong and this one is the correct one :

 if ((Spn != 3064) || (Fmi != 11) && (Fmi != 16))

I really don't get it. it is exactly opposite of what I wrote before and expected to be correct! can anybody help ?


Solution

  • Based on your example output it sounds like you want to add an item to the list if:

    • Spn is not 3064 OR IF
    • Fmi is something other than 11 or 16

    Translating those two parts into code, we get:

    Spn is not 3064

    Spn != 3064
    


    Fmi is something other than 11 or 16

    or expressed another way,

    Fmi is not 11 and Fmi is not 16

     Fmi != 11 && Fmi != 16
    


    Now putting those two together using the OR in my bulleted list above, you get:

    Spn != 3064 || (Fmi != 11 && Fmi != 16)
    


    And we can optionally remove the parentheses because && has a higher precedence than ||:

    Spn != 3064 || Fmi != 11 && Fmi != 16
    

    And this is exactly the expression that you yourself found to work.


    It might be easier to put everything in terms of what you want to skip rather than what to add. In other words,

    Skip a pair if:

    • Spn is 3064 AND
    • Fmi is 11 or 16

    So

    Spn == 3064 && (Fmi = 11 || Fmi == 16)
    

    (the parentheses are necessary this time)

    if (Spn == 3064 && (Fmi = 11 || Fmi == 16))
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   skipped", Spn, Fmi);
    }
    else
    {
        Console.WriteLine("Spn:{0}  Fmi:{1}   Added", Spn, Fmi);
    }