29 out of 43 rated this helpful - Rate this topic

switch (C# Reference)

Updated: May 2010

The switch statement is a control statement that selects a switch section to execute from a list of candidates.

Each switch section contains one or more case labels and a list of one or more statements. The following example shows a simple switch statement that has three switch sections. Each switch section has one case label, such as case 1, and a list of two statements.

int caseSwitch = 1;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}


Each case label specifies a constant value. Control is transferred to the switch section whose case label contains a constant value that matches the value of the switch expression, caseSwitch. If no case label contains a matching value, control is transferred to the default section, if there is one. If there is no default section, no action is taken and control is transferred outside the switch statement. In the previous example, the statements in the first switch section are executed because case label case 1 specifies the value 1, and the value of caseSwitch also is 1.

A switch statement can include any number of switch sections, and each section can have one or more case labels. However, no two case labels can contain the same constant value.

Execution of the statement list in the selected section begins with the first statement and proceeds through the statement list, typically until a jump statement is reached, such as a break, goto, or return. At that point, control is transferred outside the switch statement or to another case label.

Unlike C++, C# does not allow execution to continue from one switch section to the next. The following code causes an error.

switch (caseSwitch)
{
    // The following switch section causes an error.
    case 1:
        Console.WriteLine("Case 1...");
        // Add a break or other jump statement here.
    case 2:
        Console.WriteLine("... and/or Case 2");
        break;
}

The requirement in C# is that the end of every switch section, including the final one, is unreachable. Although this requirement usually is met by using a jump statement, the following case also is valid, because the end of the statement list cannot be reached.

case 4:
    while (true)
        Console.WriteLine("Endless looping. . . .");

The following example illustrates the requirements and capabilities of a switch statement.

class SwitchTest2 
{
    static void Main()
    {
        int n = 2;
        switch(n) 
        {
            case 1:
            case 2: 
            case 3: 
                Console.WriteLine("It's 1, 2, or 3.");
                break; 
        default: 
            Console.WriteLine("Not sure what it is.");
            break; 
        }
    }
}
//  Output: It's 1, 2, or 3.



In the final example, string input is converted to an integer variable, switchExp, which is used for the switch expression. You also can use the string variable, str, directly. To do that, you would change the case labels to specify string values, as is shown in the following code.

switch(str)
{
    case "1":
        // ...
    case "2":
        // ...
}
    class SwitchTest 
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
        Console.Write("Please enter your selection: "); 
        string s = Console.ReadLine(); 
        int n = int.Parse(s);
        int cost = 0;
        switch(n)
        {
        case 1:
            cost += 25;
            break;
        case 2:
            cost += 25;
            goto case 1;
        case 3:
            cost += 50;
            goto case 1;
        default:
            Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
            break;
        }
        if (cost != 0)
        {
            Console.WriteLine("Please insert {0} cents.", cost);
        }
        Console.WriteLine("Thank you for your business.");
    }
}
    /*
        Sample Input: 2

        Sample Output:
        Coffee sizes: 1=Small 2=Medium 3=Large
        Please enter your selection: 2
        Please insert 50 cents.
        Thank you for your business.
    */


For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Date

History

Reason

May 2010

Reviewed the topic for clarity and specificity.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
switch with string variables
Hi,
I'm trying to do the following:

switch

( icsName )

{

case"Beclomethasone MDI 40 (Qvar)" : case"Beclomethasone MDI 80 (Qvar)" : case"Ciclesonide MDI 80 (Alvesco)" : case trialString :

icsOrderStrings.Add(

"Add 2 puffs");

icsOrderStrings.Add(

"Add 4 puffs"); break;

I'd like to set trialString programmatically but the compiler insists on a constant. Is that how it's supposed to behave? Is there some way around this constraint?

Thank you.


SJ at MSFT edit: Switch statements in C# are defined to use constant values in the case labels. Why not use an if statement?
Using a return as the jump statement
If you're in a method that returns a value, you can use the switch statement to return a value.

public static string GreetingMessage()
{
string ActivationCountry = "United States";

switch(ActivationCountry)
{
case "Canada":
return "Welcome to Canada";
case "United States":
return "Welcome to the United States";
default:
return "Welcome!";
}
}

This example shows you don't have to always use the break statement to jump out of the switch.
Switch where multiple case's execute the same statement
Here's how you can execute the same statement(s) for multiple case's
The following is best practice on how you should handle cases that do the same logic when hit.
using fall through on the case:
        int x = 1;
switch ( x )
{
case 1:
case 2:
/* code here */
break;
case 3:
/* code here */
break;
default:
break;
}

The following while doable should not be used because it promotes unreadable code, adding to complexity and potential for bugs:
Or use goto case statements:
        int x = 1;
switch ( x )
{
case 1:
goto case 2;
case 2:
goto case 5;
break;
case 3:
/* code here */
break;
case 4:
goto case 2;
break;
case 5:
/* code here */
break;
case 6:
/* code here */
break;
case 7:
goto case 5;
break;
case 8:
/* code here */
break;
case 9:
goto case 2;
break;
default:
break;
}