0

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.

Serge
  • 63
  • 1
  • 1
  • 8
  • I don't think you mean `x == (a || b)` I think you're looking for a DRY (_don't repeat yourself_) version of `(x == a) || (x == b)` Do I understand correctly? If so, you can make an array of options like `array = new Animal[] { Animal.Dolphin, Animal.Whale }` and then ask `array.Contains(choice)`. – Wyck Apr 25 '23 at 20:20

1 Answers1

1

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))
{
    // ...
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132