Search code examples
c#if-statement

if statements matching multiple values


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.


Solution

  • How about:

    if (new[] {1, 2}.Contains(value))
    

    It's a hack though :)

    Or if you don't mind creating your own extension method, you can create the following:

    public static bool In<T>(this T obj, params T[] args)
    {
        return args.Contains(obj);
    }
    

    And you can use it like this:

    if (1.In(1, 2))