TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Nested Switch Statement

This C# example program demonstrates nested switch statements. Switch improves performance.

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.

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.

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.

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

ContainsChars returns a boolean value. This indicates whether the constant string was found in a case-insensitive way in the source string. The execution engine evaluates the switch expression one to four times per character checked.

And: If all four nested expressions match a case in each switch label section, the method returns true.

Bool Methods, Return True and FalseSwitch Char

You can see that the method returns true for the first two parameters and then false for the second two parameters. This provides a basic correctness check that shows that the method works.

Tip: This logic could be used in websites that must check if a browser's HTTP header requests contain a "gzip" string.

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

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 String Search Example

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf