Home
Search
C# Switch Char ExampleUse the switch statement on a char variable. Lowercase and uppercase chars can be handled the same way with a switch.
dot net perls
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.
Char
Switch
Required input, output. Suppose we want to expand single-char abbreviations into full strings. We can implement this with a C# switch statement.
Input and output:
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.
SwitchChar With switch, this method tests if the char is equal to a known character value. The default case deals with all other cases.
Cases The 3 cases S, T, and U in the switch are stacked on other cases. We normalize data and treat "s" and "S" equivalently.
Case
C# 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"; } } } }
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.
If
Home
© 2007-2021 sam allen. see site info on the changelog