Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence of is/not/or/and in C#

Tags:

c#

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)
like image 426
Bryce Wagner Avatar asked Dec 29 '25 14:12

Bryce Wagner


2 Answers

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.

like image 81
Bryce Wagner Avatar answered Jan 01 '26 03:01

Bryce Wagner


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)
like image 44
Ε Г И І И О Avatar answered Jan 01 '26 03:01

Ε Г И І И О