Comparing a variable to multiple values [duplicate]

Quite often in my code I need to compare a variable to several values :

if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt )
{
  // Do stuff
}

I keep on thinking I can do :

if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) )
{
   // Do stuff
}

But of course thats SQL that allows this.

Is there a tidier way in C#?


You could do with with .Contains like this:

if (new[] { BillType.Receipt, BillType.Bill, BillType.Payment}.Contains(type)) {}

Or, create your own extension method that does it with a more readable syntax

public static class MyExtensions
{
    public static bool IsIn<T>(this T @this, params T[] possibles)
    {
        return possibles.Contains(@this);
    }
}

Then call it by:

if (type.IsIn(BillType.Receipt, BillType.Bill, BillType.Payment)) {}

There's also the switch statement

switch(type) {
    case BillType.Bill:
    case BillType.Payment:
    case BillType.Receipt:
        // Do stuff
        break;
}