C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: This code takes an arbitrary char value, which is returned from the char.Parse method, and passes the char as an argument to the SwitchChar method.
Note: The SwitchChar method uses the switch control statement. It uses the switch statement on chars.
SwitchChar: This method tests if the char is equal to known character value, or if it is not. The default case deals with all other cases.
Cases: The 3 cases S, T, and U in the switch are stacked on other cases. This is a way to normalize data and treat "s" and "S" equivalently.
CaseC# program that switches on char
using System;
class Program
{
static void Main()
{
char input1 = char.Parse("s");
string value1 = SwitchChar(input1);
char input2 = char.Parse("c");
string value2 = SwitchChar(input2);
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(SwitchChar('T'));
}
static string SwitchChar(char input)
{
switch (input)
{
case 'a':
{
return "Area";
}
case 'b':
{
return "Box";
}
case 'c':
{
return "Cat";
}
case 'S':
case 's':
{
return "Spot";
}
case 'T':
case 't':
{
return "Test";
}
case 'U':
case 'u':
{
return "Under";
}
default:
{
return "Deal";
}
}
}
}
Output
Spot
Cat
Test
So: The value of the switch value is used to find the correct case. This is faster than using if-statements in common situations.
Switch EnumReview: The switch statement on char is compiled into an efficient jump table, often providing faster lookup than if-statements.