Search code examples
c#if-statementcontainslogical-operators

When should I use a contains method instead of logical operators in a c# if statement?


My colleague said I should be using an array.contains() in my if statements when evaluating enums.

example a:

if (new[] { enumvalue.a, enumvalue.b, enumvalue.c }.Contains(x.some_enum_value))
{
    do_something();
}

...vs example b:

if (x.some_enum_value == enumvalue.a || x.some_enum_value == enumvalue.b || x.some_enum_value == enumvalue.c) 
{
    do_something();
}

When should I use example a over example b?


Solution

  • Best of both worlds using enum constraint in C# 7.3:

    public static bool IsIn<TEnum>(this TEnum source, params TEnum[] list)
       where TEnum : Enum 
       => list.Contains(source);
    

    or if you will:

    public static bool IsIn<T>(this T source, params T[] list)
       => list.Contains(source);
    

    Usage:

    var someEnum = MyEnum.Three;
    
    if (someEnum.IsIn(MyEnum.One, MyEnum.Three))
    {
       Console.WriteLine();
    }
    
    var list = new[]
                  {
                     MyEnum.Three,
                     MyEnum.One
                  };
    
    if (someEnum.IsIn(list))
    {
       Console.WriteLine();
    }
    

    Note : in short, you should do what you like the most, and what's most maintainable, and also what your boss likes. Everything else is subjective.

    Note 2 : The only advantage is the extension method usage, and it can take a list of parameters using the params keyword. Otherwise, there is not much value in this.