What is the order of precedence for pattern matching "is not"? I realized I've written some code like this:
if (x is not TypeA or TypeB)
And implicitly assumed I was writing:
if (!(x is TypeA) && !(x is TypeB))
But I just realized that it might be evaluating as:
if ((!x is TypeA) || (x is TypeB))
In other words, does the "not" apply to an "or separated" list, or does it just apply to the next argument in the list. Does my original statement need to be written as this instead:
if (x is not TypeA and not TypeB)
Here's a test program:
class A { }
class B : A { }
class C : A { }
A a1 = new A();
A a2 = new B();
A a3 = new C();
Console.WriteLine("A is not B or C " + (a1 is not B or C));
Console.WriteLine("B is not B or C " + (a2 is not B or C));
Console.WriteLine("C is not B or C " + (a3 is not B or C));
Console.WriteLine("A is not (B or C) " + (a1 is not (B or C)));
Console.WriteLine("B is not (B or C) " + (a2 is not (B or C)));
Console.WriteLine("C is not (B or C) " + (a3 is not (B or C)));
Console.WriteLine("A is not B and not C " + (a1 is not B and not C));
Console.WriteLine("B is not B and not C " + (a2 is not B and not C));
Console.WriteLine("C is not B and not C " + (a3 is not B and not C));
And here's the output:
A is not B or C True
B is not B or C False
C is not B or C True
A is not (B or C) True
B is not (B or C) False
C is not (B or C) False
A is not B and not C True
B is not B and not C False
C is not B and not C False
So "is not (B or C)" is the same as "is not B and not C".
But "is not B or C" checks that it's not B or is C, which is probably never something you want to do.
If you want
if (x != TypeA || x != TypeB)
You should write
if (x is not TypeA or not TypeB)
Same goes for AND
if (x != TypeA && x != TypeB)
if (x is not TypeA and not TypeB)
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