Is there are a way to achieve the following in .net6:
if (x != (a || b)) { Do something }
for when a or b are not Boolean values?
Specifically a case when x,a and b are enums or numeric values like this:
enum Animal : byte {
Cat,
Dog,
Cow,
Dolphin,
Horse,
Whale
}
Later we want to evaluate the state of a variable, lets say a user has to make a choice:
if (choice == (Animal.Dolphin || Animal.Whale)) {
Console.WriteLine("Lives in the sea");
}
I know this could be achieved with a switch statement but wondering if there is a way one can do it more compact like with a multi optional comparison inside an if statement.
>Solution :
You can use pattern matching with is operator:
if (choice is Animal.Dolphin or Animal.Whale)
{
// ...
}
It also supports negation patterns (C# 9):
if (choice is not (Animal.Dolphin or Animal.Whale))
{
// ...
}