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:
and
>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