Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading