Understanding Switch Statement Fallthrough in C#
In C#, switch statements allow program flow to be directed based on a given variable's value. However, traditional if/else constructs lack the ability to "fall through" different cases like switch statements do.
Consider the following example, which attempts to convert a number to its word representation:
static string NumberToWords(int number) { string[] numbers = new string[] { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string[] tens = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; string[] teens = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string ans = ""; switch (number.ToString().Length) { case 3: ans += string.Format("{0} hundred and ", numbers[number / 100]); case 2: int t = (number / 10) % 10; if (t == 1) { ans += teens[number % 10]; break; } else if (t > 1) ans += string.Format("{0}-", tens[t]); case 1: int o = number % 10; ans += numbers[o]; break; default: throw new ArgumentException("number"); } return ans; }
When this code is compiled, it fails with errors indicating that control cannot fall through from one case to another. This issue stems from the fact that in C#, a switch statement requires explicit breaks after each case to ensure that the flow of execution is controlled.
Achieving Fallthrough
To achieve fallthrough in a switch statement, there are three options:
Example with Fallthrough
The following modified version of the NumberToWords function utilizes the goto case syntax to achieve fallthrough:
static string NumberToWords(int number) { string[] numbers = new string[] { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; string[] tens = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; string[] teens = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string ans = ""; switch (number.ToString().Length) { case 3: ans += string.Format("{0} hundred and ", numbers[number / 100]); goto case 2; case 2: int t = (number / 10) % 10; if (t == 1) { ans += teens[number % 10]; break; } else if (t > 1) ans += string.Format("{0}-", tens[t]); goto case 1; case 1: int o = number % 10; ans += numbers[o]; break; default: throw new ArgumentException("number"); } return ans; }
The above is the detailed content of How Can I Achieve Fallthrough Behavior in C#'s Switch Statements?. For more information, please follow other related articles on the PHP Chinese website!