switch char ExampleUse the switch statement on a char variable. Lowercase and uppercase chars can be handled the same way with a switch.
This page was last reviewed on Sep 12, 2023.
Switch char. In C# programs the switch can handle char cases. Because a char is a value, switch can use jump tables to test chars.
Some uses. 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.
Required input, output. 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 ...
An example. 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.
Info This code takes a char value (returned from the char.Parse method). It passes the char as an argument to the SwitchChar method.
Detail With switch, this method tests if the char is equal to a known character value. The default case deals with all other cases.
Detail The 3 cases S, T, and U in the 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
Internals. 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.
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 enum
A summary. 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, review. The 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 12, 2023 (edit).
© 2007-2024 Sam Allen.