Subject: C# switch statement
Posted By: nalla Post Date: 12/9/2005 5:36:40 AM
Hi,

C# switch statement has designed to not allow fall-through, but still  why does it require a break?

Reply By: Ankur_Verma Reply Date: 12/9/2005 9:47:22 AM
Well if you would see, the break statement is needed in the default block as well. Thats because its not the
break statement thats needed its the requirement of all the blockes under switch to have a 'jump statement'.
Commomnly you provide the break statement so thats what you see, but it can be any jump statement.

Regards
Ankur Verma
Reply By: Doknjas Reply Date: 12/9/2005 7:28:23 PM
This is mainly to be consistent with C and C++, and to avoid confusion for programmers from that background.  Strictly speaking, it should not be necessary.

Also, be aware that C# switches do allow fall-through for empty cases:
e.g.,
switch (x)
{
  case 1:
  case 2:
     ...
     break;
}



Reply By: nalla Reply Date: 12/12/2005 11:01:45 PM
Hi,

switch(value)
{
  case 0:
    printf(In case 0\n);
  case 1:
    printf(In case 1\n);
  case 2:
    printf(In case 2\n);
    break;
}

C/C++ allows us to use the switch statement like this without a break statement and this will result,

In case 0
In case 1
In case 2

But why can't use use the switch statement without a break or any jump statement in C# like we are using in C/C++?

I know we can implement fall-through in C# using "goto" in each case like, but C# still requires a jump statement.
switch(value)
{
  case 0:
    printf(In case 0\n);
    goto case 1;
  case 1:
    printf(In case 1\n);
    goto case 2;
  case 2:
    printf(In case 2\n);
    break;
}


Reply By: Ankur_Verma Reply Date: 12/14/2005 4:31:35 AM
Well nalla I must say that the case you've presented here needs to be re-thought for it design.
I would say that empty case blocks make sense with fallthrougs and C# does support that as Doknjas
mentioned. But with non-empty case blocks, if fallthroughs are not supported, i find it a welcome change.

Also, I dare say, you dont face situations where fall throughs are required as often as as those
where they are not. So if you want fall though supported even with non empty cases blocks, you are
actually asking support for the exception rather than for the norm as they call it.

In C++ where fall through for non empty case blocks is supported, is easier to program a logical error thats
hard to spot latter on. C# is 'safer' that way.

Regards
Ankur Verma

Go to topic 37601

Return to index page 417
Return to index page 416
Return to index page 415
Return to index page 414
Return to index page 413
Return to index page 412
Return to index page 411
Return to index page 410
Return to index page 409
Return to index page 408