switch

suggest change

The switch statement is a control statement that selects a switch section to execute from a list of candidates. A switch statement includes one or more switch sections. Each switch section contains one or more case labels followed by one or more statements. If no case label contains a matching value, control is transferred to the default section, if there is one. Case fall-through is not supported in C#, strictly speaking. However, if 1 or more case labels are empty, execution will follow the code of the next case block which contains code. This allows grouping of multiple case labels with the same implementation. In the following example, if month equals 12, the code in case 2 will be executed since the case labels 12 1 and 2 are grouped. If a case block is not empty, a break must be present before the next case label, otherwise the compiler will flag an error.

int month = DateTime.Now.Month; // this is expected to be 1-12 for Jan-Dec

switch (month)
{
    case 12: 
    case 1: 
    case 2:
        Console.WriteLine("Winter");
        break;
    case 3: 
    case 4: 
    case 5:
        Console.WriteLine("Spring");
        break;
    case 6: 
    case 7: 
    case 8:
        Console.WriteLine("Summer");
        break;
    case 9:     
    case 10: 
    case 11:
        Console.WriteLine("Autumn");
        break;
    default:
        Console.WriteLine("Incorrect month index");
        break;
}

A case can only be labeled by a value known at compile time (e.g. 1, "str", Enum.A), so a variable isn’t a valid case label, but a const or an Enum value is (as well as any literal value).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents