Multi-variable switch statement in C#

BanditoBunny picture BanditoBunny · Nov 1, 2011 · Viewed 43.7k times · Source

I would like use a switch statement which takes several variables and looks like this:

switch (intVal1, strVal2, boolVal3)
{
   case 1, "hello", false:
      break;
   case 2, "world", false:
      break;
   case 2, "hello", false:

   etc ....
}

Is there any way to do something like this in C#? (I do not want to use nested switch statements for obvious reasons).

The question was answered by .net dev team by implementing of exactly this fearture: Multi-variable switch statement in C#

Answer

Stephen Kennedy picture Stephen Kennedy · May 26, 2018

You can do this in C# 7 and higher with the when keyword:

switch (intVal1)
{
    case 1 when strVal2 == "hello" && boolVal3 == false:
        break;
    case 2 when strVal2 == "world" && boolVal3 == false:
        break;
    case 2 when strVal2 == "hello" && boolVal3 == false:
        break;
}