if statements matching multiple values

Viewed 179947

Any easier way to write this if statement?

if (value==1 || value==2)

For example... in SQL you can say where value in (1,2) instead of where value=1 or value=2.

I'm looking for something that would work with any basic type... string, int, etc.

16 Answers

C# 9 supports this directly:

if (value is 1 or 2)

however, in many cases: switch might be clearer (especially with more recent switch syntax enhancements). You can see this here, with the if (value is 1 or 2) getting compiled identically to if (value == 1 || value == 2).

You can use the switch statement with pattern matching (another version of jules's answer):

if (value switch{1 or 3 => true,_ => false}){
  // do something
}
Related