C#: I miss case fall through
We all have heard time and again that the default case fall through is not good (as in C/C++) and C# does not allow it. There has been enough debate on this but I still differ on this. I used to like it a lot and somehow when I do need to use it the following puts me off big time!!!
switch(value){ case 0: Console.WriteLine("In case 0\n"); gotocase 1; case 1: Console.WriteLine("In case 1\n"); gotocase 2; case 2: Console.WriteLine("In case 2\n"); break;}
I kind of do not buy the statement that case-statement fall through results in issues in the maintainence phase. Its pointed out that fall-through can lead to the following
- Developer forgets to add the break at the end and un-intentional fall-through may happen
- Case statements cannot be easily reordered as the fall-through execution may vary...
With C lying around for 30 years and C++ over 20 years most developers have got used to adding break at the end of case. In case C# wanted to do something for new developers or for developers moving in from languages like VB, a warning could have been added in case break is missing, asking the developer if fall-through is the intent. This is very similiar to the warning given for the following code
bool hello;// lots of code....
if (hello = true) // this is why some people use true == hello Console.WriteLine(arg);
Warning 1 Assignment in conditional expression is always constant; did you mean to use == instead of = ?
What I also do not understand is the requirement for the break statement at the end of each case in C# even though it does not support fall-through.
switch (arg){ case "0": Console.WriteLine(0); //break; case "1": Console.WriteLine(1); break;}
The above code fails to compile and you need to uncomment the //break to get it to compile. The error is "Control cannot fall through from one case label ('case "0":') to another" Since the language clearly states that fall-through do not happen then why do I need to add the extra break, it has no purpose and I should not be required to add it. This looks like to have been added to aid C/C++ developers to understand that fall through does not happen. I feel that this error should have been the warning I had mentioned above....
There are a lot of interesting or weird uses of fall-through and the fact that switch can be interlaced with statement blocks (thats in the next post...).