Like it

Sunday, July 10, 2011

Select Case Statement in C# / C-sharp

Switch Case Statement in C# (.NET)

Here is an example of Select Case like construct using C#:

private string ShirtSizes(int ShirtSize) 
switch (ShirtSize) 
case 36: 
return "Small"; 
case 38: 
return "Medium"; 
case 40: 
return "Large"; 
case 42: 
return "Extra Large"; 
case 44: 
return "XXL"; 
default: 
return "Free Size"; 
}  

Fall-Thru in Switch Case Statement in C#(Csharp)

Fall through can be achieved as follows:

switch (ShirtSize) 
case 34: 
case 35: 
case 36: 
return "Small"; 
case 38: 
return "Medium";  ...   

The Switch construct requires jump statements like GoTo or Break to transfer control outside the loop. Else it will throw an Error Control cannot fall through from one case label ### to another

To avoid this use break / goto statements. On the other hand if you use more than one jump statement for a case - like the one shown below - you will get Unreachable code detected warning

case 38: 
return "Medium"; 
break;                 


No comments:

Post a Comment