Wednesday, January 06, 2010

switch, default and break in C#

When you "switch" from C++ to C# and want to use "switch" statement, do not forget on of the major differences between switch in C++ and switch in C#:

Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. (here)

Even default must have it's own break now - otherwise you'll get a following message from compiler:

Control cannot fall through from one case label ('default:') to another.

So, do not forget break for default

switch(...)
{
case ...:
...
break;
...
default:
...
break; // !!!
}


and enjoy!

No comments: