Comparing a variable to multiple values

C#

C# Problem Overview


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#?

C# Solutions


Solution 1 - 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)) {}

Solution 2 - C#

There's also the switch statement

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

Solution 3 - C#

Assuming type is an enumeration, you could use the FlagsAttribute:

[Flags]
enum BillType
{
    None = 0,
    Bill = 2,
    Payment = 4,
    Receipt = 8
}

if ((type & (BillType.Bill | BillType.Payment | BillType.Receipt)) != 0)
{
    //do stuff
}

Solution 4 - C#

Try using a switch

 switch (type)
    {
        case BillType.Bill:
        case BillType.Payment:

        break;
    }

Solution 5 - C#

Try using C# HashSet for list of values. This can be especially useful if you need to compare many values to single set of values.

Solution 6 - C#

Try checking out the Strategy Design Pattern (a.k.a. the Policy Design Pattern).

public interface IBillTypePolicy
{
    public BillType { get; }
    void HandleBillType();
}
public class BillPolicy : IBillTypePolicy
{
    public BillType BillType { get { return BillType.Bill; } }

    public void HandleBillType() 
    { 
        // your code here...
    }
}

Here's a great post on how to dynamically resolve the policy from Los Techies.

Solution 7 - C#

What about getting an array of all Enums values and iterate through this?

http://maniish.wordpress.com/2007/09/27/iterate-through-enumeration-c/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMongus PongView Question on Stackoverflow
Solution 1 - C#MarkView Answer on Stackoverflow
Solution 2 - C#wasatzView Answer on Stackoverflow
Solution 3 - C#Yuriy FaktorovichView Answer on Stackoverflow
Solution 4 - C#bleeeahView Answer on Stackoverflow
Solution 5 - C#Sergiy BelozorovView Answer on Stackoverflow
Solution 6 - C#Jarrett MeyerView Answer on Stackoverflow
Solution 7 - C#p.marinoView Answer on Stackoverflow