HomeSearch

C# Nested Switch Statement

Use nested switch statements to perform more complicated logic with switch.
Nested switch. A switch can be nested. This sometimes achieves performance gains in methods that must search many values in a loop. We can search for a constant string or pattern in an array. Nested switches handle two patterns with jump tables.Switch
Example. When you apply the switch selection statement, the switch expression is evaluated. Its actual value is adjusted to point to an offset in the intermediate language. It essentially provides a tiny hash table implemented with jump tables.

ContainsChars: This returns a boolean value. This indicates whether the constant string was found in a case-insensitive way in the source string.

Bool MethodSwitch Char

Here: We search for the four characters "gzip" in that order in a case-insensitive way. We use four nested switch statements in a loop.

Note: We treat the current character based on the induction variable loop index. We then check the next three characters.

Main: This provides a basic correctness check that shows that the method works. Having a correct method is important.

C# program that uses nested switch statements using System; class Program { static bool ContainsChars(string value) { // // Uses three nested switch statements in a loop to scan character patterns. // for (int i = 0; i < value.Length - 3; i++) { switch (value[i]) { case 'g': case 'G': switch (value[i + 1]) { case 'z': case 'Z': switch (value[i + 2]) { case 'i': case 'I': switch (value[i + 3]) { case 'p': case 'P': return true; } break; } break; } break; } } return false; } static void Main() { // // Test the output of the nested switch method. // Console.WriteLine(ContainsChars("GZip")); Console.WriteLine(ContainsChars("deflate, gzip")); Console.WriteLine(ContainsChars("zgip")); Console.WriteLine(ContainsChars("Gzi")); } } Output True True False False
Discussion. This method is not usually an ideal way to check for a substring inside another string case-insensitively. Most developers will prefer to use the IndexOf method and pass StringComparison.OrdinalIgnoreCase.IndexOfStringComparison, StringComparer
However, the method here can scan the strings encountered on the Internet from browsers in about 4.13 nanoseconds, rather than 87.09 nanoseconds. This makes it about 21 times faster.

Also: A method that uses if-statements instead of the nested switch statements is about 0.3 nanoseconds slower per call.

Boyer-Moore: Another option is the Boyer-Moore string search. This skips ahead once an invalid character is found.

Boyer-Moore
Summary. We looked at a nested char switch statement. It is possible to build a method that uses several switch statements inside each other to have better performance in the method body at the cost of more apparent complexity.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls