Switch#
We briefly introduced switch in section switch, but did not use it.
var state = BrewingState.Idle;
while (true)
switch (state)
{
case BrewingState.Idle:
Console.WriteLine("Idle 💤");
Console.Write("Press 's' to start brewing: ");
if (Console.ReadLine() == "s")
state = BrewingState.Brewing;
break;
case BrewingState.Brewing:
Console.WriteLine("Brewing 🌊");
await Task.Delay(2000);
state = BrewingState.Done;
break;
case BrewingState.Done:
Console.WriteLine("DONE ☕");
Console.Write("Press 'e' to exit or 'r' to restart: ");
var input = Console.ReadLine();
if (input == "e") return;
if (input == "r") state = BrewingState.Idle;
break;
}
internal enum BrewingState
{
Idle,
Brewing,
Done
}
Tip
Use switch if you have have to take actions based on the value of a single variable.
Note that enumerated variables behave like numbers when used with mathematical operators. They get the numbers beginning from 0.
Console.WriteLine(BrewingState.Idle - BrewingState.Brewing);
internal enum BrewingState
{
Idle,
Brewing,
Done
}
Output:
-1
Activity 29 (RPSSL resolution logic)
Fig. 21 rock paper scissors lizard Spock resolution diagram
CC BY-SA 3.0. By DMacks (talk). Source: Wikimedia Commons#
RPSSL shapes can be resolved with the following table if we attach numbers from 0 to 4.
p2-p1 |
p1 … |
|---|---|
0 |
tie |
-4 or -2 or 1 or 3 |
wins |
-3 or -1 or 2 or 4 |
loses |
Steps:
Define an enumerated type for different shapes
Implement the resolution table using a switch statement and put this into a function
Test your function with the following code.
Hint: In a switch statement, you can combine many cases like this: case "geko" or "gökçe".
The following code iterates over every combination of shape pairs and writes the iterated shape names. Add your function to the loop body to test your function for every shape combination possible.
Enum.GetValues<Shape>() gets the enumeration values inside the enum type Shape. So pay attention that your enumeration type’s name is called Shape, or change the following code according to your enumeration type.
foreach (var p1 in Enum.GetValues<Shape>())
foreach (var p2 in Enum.GetValues<Shape>())
Console.WriteLine($"If p1: {p1} and p2: {p2} => ");
// Print Win lose or tie.
Appendix#
If you are interested where the resolution table comes from, refer here.