p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   General .NET (http://p2p.wrox.com/forumdisplay.php?f=122)
-   -   C# switch statement (http://p2p.wrox.com/showthread.php?t=35956)

nalla December 9th, 2005 06:36 AM

C# switch statement
 
Hi,

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


Ankur_Verma December 9th, 2005 10:47 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

Doknjas December 9th, 2005 08:28 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;
}




nalla December 13th, 2005 12:01 AM

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;
}



Ankur_Verma December 14th, 2005 05:31 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


All times are GMT -4. The time now is 04:02 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.