Matthew Scharley Matthew Scharley - 1 year ago 118
C# Question

Switch statement fallthrough in C#?

Switch statement fallthrough is one of my personal major reasons for loving

if/else if
constructs. An example is in order here:

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];
else if (t > 1)
ans += string.Format("{0}-", tens[t]);
case 1:
int o = number % 10;
ans += numbers[o];

throw new ArgumentException("number");
return ans;

The smart people are cringing because the
s should be declared outside the function: well, they are, this is just an example.

The compiler fails with the following error:

Control cannot fall through from one case label ('case 3:') to another
Control cannot fall through from one case label ('case 2:') to another

Why? And is there any way to get this sort of behaviour without having three

Answer Source

(Copy/paste of an answer I provided elsewhere)

Falling through switch-cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms:

switch (/*...*/) {
    case 0: // shares the exact same code as case 1
    case 1:
        // do something
        goto case 2;
    case 2:
        // do something else
        goto default;
        // do something entirely different
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download