C # How to use "||" combined with "! ="?

Why adding "||" OR between 2 "! =" Doesn't work for me?

When "name" is "test" or "test2", my if statement doesn't work if I used 2 "! =", But if I only use one of them, please tell me why.

if (col.Name != "test" || col.Name != "test2")
 {
  MessageBox.Show("No" + col.Name.ToString()); //This shows "No test" and "No test2"
 }
  else
 {
  MessageBox.Show("YES " + col.Name.ToString()); //does not reach here
 }

      

this works without "||".

if (col.Name != "test")
 {
  MessageBox.Show("No" + col.Name.ToString());
 }
  else
 {
  MessageBox.Show("YES " + col.Name.ToString()); //Shows "YES test"
 }

      

Thanks everyone

0


source to share


4 answers


try this:

col.Name != "test" && col.Name != "test2"

      



think about it ... "if the number is not 1 or the number is not 2" will always be true since the number is 1 and 2 so that both halves are false. Now let's extend this to strings.

+17


source


It works, but it is not what you want.

col.Name != "test" || col.Name != "test2"

      



always returns true , because if col.Name is "test" it is not "test2", so you have "false || true" => true. If col.Name is "test2", you get "true || false". If it is anything else, it evaluates to "true || true".

I can't tell you exactly what you want to do, but you probably need a and ( &&

) in between.

+7


source


You need to do AND, not OR :)

Pseudocode:

if string1 is not equal to test AND is not equal to test2 than do ...

Here's the revised version:

if (col.Name != "test" && col.Name != "test2")
{
  MessageBox.Show("No" + col.Name.ToString()); //This shows "No test" and "No test2"
}
else
{
  MessageBox.Show("YES " + col.Name.ToString()); //does not reach here
}

      

+4


source


You use OR, count the truth table:

p          q        p || q
true      true      true
true      false     true
false     true      true
false     false     false

      

You have to use AND for the desired behavior ...

+4


source







All Articles