Use pattern mattching to detect x is not a or not b

I need to check if some value is not one or another and I want to use or with pattern matching. The "forward" one – x is a o b is easy:

int GetInt() => 3;

if (GetInt() is 3 or 4)
{
    Console.WriteLine("3 or 4");
}

But negation I can’t figure out. I tried:

if (GetInt() is not 4 or 3)
{
    Console.WriteLine("not 3 or 4 #1");
}
else
{
    Console.WriteLine("Succcess");
}

Or

if (GetInt() is not 3 or not 4)
{
    Console.WriteLine("not 3 or 4 #2");
}
else
{
    Console.WriteLine("Succcess");
}

But both print the first statement (the not 3 or 4...).

Also IDE grays out different parts of the code:

enter image description here

and

enter image description here

>Solution :

You can just use parenthesis:

if (GetInt() is not (3 or 4))
{
    Console.WriteLine("not 3 or 4 #2");
}
else
{
    Console.WriteLine("Success");
}

Demo @sharplab.io

Leave a Reply