Archive

Posts Tagged ‘switch’

[C#] Using the switch case Statement

Saturday, 26 April, 2008 1 comment

The switch statement chooses flow of control based on the evaluation of a
numeric or string comparison.The switch statement does not allow control to fall
through to the next case as in C/C++ unless the case statement is followed
immediately by another case statement. In other words, you must use a break statement
with every case statement.You can also use a goto statement, although most
programmers frown on using them. Here are two examples:

int j = 0;
int i = 1;
switch (i)
{
case 1:j = 7;break;
case 2:
case 3:j = 22;break;
default:j = 33; break;
}

string lastName = “”;
string text = “fred”;
switch ( text )
{
case “fred”:lastName = “Flinstone”;break;
case “barney”:lastName = “Rubble”;break;
default:lastName = “Slate”;break;
}

Categories: C# Tags: ,