char
In C# programs the switch
can handle char
cases. Because a char
is a value, switch
can use jump tables to test chars.
We can take a char
value and get a full string
version of it—using the switch
statement on characters. Ranges of characters can be specified as multiple cases.
Suppose we want to expand single-char
abbreviations into full strings. We can implement this with a C# switch
statement.
a -> Area b -> Box c -> Cat ...
There are several ways of looking up characters and getting equivalent values for them. Some options include if conditional statements, switch
statements, and lookup tables.
char
value (returned from the char.Parse
method). It passes the char
as an argument to the SwitchChar
method.switch
, the SwitchChar
method tests if the char
is equal to a known character value. The default case deals with all other cases.switch
are stacked on other cases. We normalize data and treat "s" and "S" equivalently.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"; } } } }Spot Cat Test
Char
switches result in the jump table instruction. Jump tables are a way to achieve much faster look up by using multiplication and addition instructions.
switch
value is used to find the correct case. This is faster than using if
-statements in common situations.We can switch
on the character type in the C# language. This is an efficient (and terse) way to find the values of individual characters.
Char
, reviewThe switch
statement on char
is compiled into an efficient jump table, often providing faster lookup than if
-statements. This pattern is worth using in C# programs.