c#: switch multiple values in case 1,2,3 using extension methods in(1,2,3)

No comments
I want to check if a variable contains one of several values, and if so do something about it.

Here's the usual switch way:

switch (value)
{
    case 1:
    case 2:
    case 3:
        //do some stuff
        break;
    case 4:
    case 5:
    case 6:
        //do some different stuff
        break;
    default:
        //default stuff
        break;
}

Does that feel ok to you?
To me it's just feels too verbose and cludgy.
In VB it's possible to write like this:

Select Case value
    Case 1 To 3
        'do some stuff
    Case 4, 5, 6
        'do some different stuff
    Case Else
        'default stuff
End Select

which is way more elegant.

So how do we get this in c#?

I ended up with this solution:

if(value.In(1,2,3))
    { /* do some stuff */ }
else if (value.In(4,5,6))
    { /* do some different stuff */ }
else
    { /*default stuff */ }

You likey - likey? ;)
And it's also more flexible than a switch statement.

The magic behind is just this sweet little extension method:

    public static class Extensions
    {
        public static bool In<T>(this T t, params T[] values)
        { return values.Contains(t); }
    }

Me likey
Henri

No comments :

Post a Comment