This article is currently in the process of being translated into Czech (~50% done).
The switch statement
Příkaz switch je jako množina příkazů if. Je to seznam možností, s akcí pro každou možnost a volitelnou výchozí akcí v případě, že nic jiného nehodnotí hodnotu true. Jednoduchý příkaz přepínače vypadá takto:
int number = 1;
switch(number)
{
case 0:
Console.WriteLine("The number is zero!");
break;
case 1:
Console.WriteLine("The number is one!");
break;
}
The identifier to check is put after the switch keyword, and then there's the list of case statements, where we check the identifier against a given value. You will notice that we have a break statement at the end of each case. C# simply requires that we leave the block before it ends. In case you were writing a function, you could use a return statement instead of the break statement.
In this case, we use an integer, but it could be a string too, or any other simple type. Also, you can specify the same action for multiple cases. We will do that in the next example too, where we take a piece of input from the user and use it in our switch statement:
Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
}
V tomto příkladu požádáme uživatele o otázku a navrhneme, aby zadali buď ano, ne nebo možná. Poté si přečteme uživatelský vstup a vytvoříme pro něj příkaz switch. Abychom uživateli pomohli, převedeme vstup na malá písmena, než je zkontrolujeme na našich malých řetězcích, takže není rozdíl mezi malými a velkými písmeny.
Přesto může uživatel provést překlep nebo zkusit napsat něco úplně jiného a v tomto případě nebude tímto specifickým příkazem přepínače generován žádný výstup. Zadejte výchozí klíčové slovo!
Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
case "yes":
case "maybe":
Console.WriteLine("Great!");
break;
case "no":
Console.WriteLine("Too bad!");
break;
default:
Console.WriteLine("I'm sorry, I don't understand that!");
break;
}
Není-li žádný z případových příkazů (case) vyhodnocen jako true, bude proveden výchozí (default) příkaz, pokud existuje. Je volitelný, jak jsme viděli v předchozích příkladech.