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

Conditional logic case (x == (a || b))

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:

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

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))
{
    // ...
}
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