DudeWhoWantsToLearn
DudeWhoWantsToLearn

Reputation: 771

Can you create a switch with multiple expressions?

I was wondering if I can use a switch with multiple expressions. For example:

string s = "A";
int i = 3;

switch (s, i)
{
    case "A", 1:
      //DoStuff
      break;
    case "A", 2:
      //DoStuff
      break;
    case "A", 3:
      //DoStuff
      break;
    ...
}

I don't want to use hundreds of if(s == "A" && i == 1)-Statements so it would be great if there's a better solution.

PS: This switch is just an example, I'm actually using it with more complex strings like Names

Upvotes: 1

Views: 144

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109792

You certainly can, for example by using tuples:

string s = "A";
int    i = 3;

switch (s, i)
{
    case ("A", 1):
        // DoStuff.
        break;

    case ("A", 2):
        // DoStuff.
        break;

    case ("A", 3):
        // DoStuff.
        break;
}

(Basically exactly what you typed, except with the addition of parenthesis in the cases to make them into tuples.)

Note that this requires C# 7 or later.

Upvotes: 4

SomeBody
SomeBody

Reputation: 8743

Since C# 7, it is possible to do the following:

string s = "A";
int i = 3;

switch (s)
{
    case "A" when i == 1:
      //DoStuff
      break;
    case "A" when i == 2:
      //DoStuff
      break;
    case "A" when i == 3:
      //DoStuff
      break;
    ...
}

Upvotes: 3

Related Questions