Home > Backend Development > C++ > How Does Fallthrough Behavior Work in C# Switch Statements, and When Should `goto case` Be Used?

How Does Fallthrough Behavior Work in C# Switch Statements, and When Should `goto case` Be Used?

Linda Hamilton
Release: 2025-01-03 06:37:40
Original
470 people have browsed it

How Does Fallthrough Behavior Work in C# Switch Statements, and When Should `goto case` Be Used?

Fallthrough Behavior in C# Switch Statements

In C#, switch statements allow for sequential execution of code when matching multiple cases. However, by default, switch statements require an explicit break statement at the end of each case to prevent unexpected behavior.

Consider the following code example:

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;
}
Copy after login

This code attempts to convert a number to its string representation. However, the switch statement raises an error stating that control cannot fall through from case 3 to case 2, and from case 2 to default. The reason for this is that in C#, switch statements require explicit breaks to prevent unintended execution of subsequent cases.

To achieve fallthrough behavior, one can use the special goto case syntax. Here's how it can be implemented in the example:

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 default;
    case 1:
        int o = number % 10;
        ans += numbers[o];

        break;
    default:
        throw new ArgumentException("number");
}
Copy after login

In this modified code, the goto case keyword allows execution to fall through to the next case, without requiring an explicit break statement. By adding a goto case 2 after case 3, the code below that case (which converts tens and ones) is executed regardless of the length of the input number. Similarly, adding goto default after case 2 ensures that the default case is always executed.

This fallthrough behavior may be desirable in certain situations, such as the conversion of digits to their corresponding word representations in the example provided. However, it is important to use it judiciously and with caution, as careless fallthrough can lead to complex and error-prone code.

The above is the detailed content of How Does Fallthrough Behavior Work in C# Switch Statements, and When Should `goto case` Be Used?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template