Skip to main content

How to Pick Code by a Value with a switch Statement in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

A switch statement takes one value and runs the statements under the case label that matches it. Here, one switch turns drink sizes such as "small" and "large" into how many millilitres each size holds, and sends any size it doesn't know to default.

A switch statement picks the code to run by comparing one value with a list of constants. The C# reference: The switch statement selects a series of statements to execute based on a pattern match with a match expression. Each case label in this post holds a constant, such as "small", and the reference describes that kind of pattern as: A constant pattern: test if an expression result equals a constant.

The value can be a string. The C# specification: The governing type of a switch statement can be the type string. So switch (size) with case "small": compares the text in size with "small".

Syntax​

Syntax
switch (<value>)
{
case <constant>:
<statements>
break;
case <constant2>:
case <constant3>:
<statements>
break;
default:
<statements>
break;
}
PartWhat it is
<value>The value to check, such as a string variable
case <constant>:A case label. The statements under it run when <value> equals <constant>
<constant>A constant value, such as the text "small" or a const
case <constant2>: and case <constant3>:Two labels stacked on one section, so either value runs the same statements
<statements>The code to run for that case
break;Ends the section and leaves the switch
default:Optional. Its statements run when no case label matches

The Example​

A console app called SwitchStatement goes through four drink sizes that customers asked for: small, regular, large and huge. For each one, a switch prints how many millilitres that size holds. The shop calls its middle size either medium or regular, so both names share one section, and it has no huge size, so that one goes to default.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n SwitchStatement
cd SwitchStatement
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/SwitchStatement/SwitchStatement.csproj:
Determining projects to restore...
Restored /Users/you/source/SwitchStatement/SwitchStatement.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n SwitchStatement creates a folder named SwitchStatement with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or SwitchStatement.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the sizes to check:

Program.cs (the sizes)
// Four drink sizes that customers asked for.
string[] orders = ["small", "regular", "large", "huge"];

orders is an array of four strings. The foreach loop below sends each one through the switch in turn.

Then the loop and the switch:

Program.cs (the switch)
foreach (string size in orders)
{
// switch runs the statements under the case whose value matches size.
switch (size)
{

switch (size) gives the switch the value to check: the size the loop is on. The case labels below say which values it looks for.

Then the first case:

Program.cs (the small case)
case "small":
Console.WriteLine($"{size}: 250 ml");
break;

When size is "small", the statements under case "small": run, and Console.WriteLine prints the size with 250 ml. Microsoft's guide to selection statements: Each case label lists a value to match, and each case section ends with a break statement. break passes control out of the switch, so the loop moves on to the next size.

Then two labels on one section, and one more case:

Program.cs (stacked labels)
case "medium":
case "regular":
Console.WriteLine($"{size}: 350 ml");
break;
case "large":
Console.WriteLine($"{size}: 500 ml");
break;

case "medium": and case "regular": sit on top of each other with nothing between them, so they share one section: either size prints 350 ml. The same guide: Stack labels to share one body, and use the default section for values that no case matches. case "large": works like case "small": and prints 500 ml.

Last, default:

Program.cs (default)
default:
Console.WriteLine($"{size}: we don't have that size");
break;
}
}

default: catches every size that no case label matches. The C# reference: The default case specifies statements to execute when a match expression doesn't match any other case pattern. A switch can have only one, because the C# specification says: There can be at most one default label in a switch statement.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
small: 250 ml
regular: 350 ml
large: 500 ml
huge: we don't have that size

macOS-style terminal window titled Terminal — SwitchStatement showing dotnet run printing small: 250 ml, regular: 350 ml, large: 500 ml, and huge: we don't have that size

Each size went to its own section. small printed 250 ml. regular has no section of its own, but its label is stacked with case "medium":, so it printed 350 ml. large printed 500 ml, and huge matched no label, so default printed huge: we don't have that size.

The Complete File​

macOS-style code window titled Program.cs — SwitchStatement showing an array of four drink sizes, a foreach loop, and a switch statement with a case for small, stacked cases for medium and regular, a case for large, each ending with break, and a default section

Program.cs
// Four drink sizes that customers asked for.
string[] orders = ["small", "regular", "large", "huge"];

foreach (string size in orders)
{
// switch runs the statements under the case whose value matches size.
switch (size)
{
case "small":
Console.WriteLine($"{size}: 250 ml");
break;
case "medium":
case "regular":
Console.WriteLine($"{size}: 350 ml");
break;
case "large":
Console.WriteLine($"{size}: 500 ml");
break;
default:
Console.WriteLine($"{size}: we don't have that size");
break;
}
}

Common Mistakes​

MistakeWhat happensDo this instead
Expecting case "large": to match "Large"With size set to "Large", the switch went to default and printed Large: we don't have that size (see the FAQ for why)Switch on a lowercase copy: switch (size.ToLowerInvariant()) printed Large: 500 ml
Writing the same value in two case labelsTwo case "small": labels stopped the build with error CS0152: The switch statement contains multiple cases with the label value '"small"'Give each value one label. To run the same code for two values, stack two different labels
Using a variable as a case labelcase biggest:, where biggest is a string variable, stopped the build with error CS9135: A constant value of type 'string' is expected. Microsoft's error reference: Variables can't be used as patterns.Declare it as a constant: with const string Biggest = "large";, case Biggest: printed large: 500 ml

FAQ​

Does a case label compare text the way == does?​

Yes. Each label here is a constant pattern, and the patterns reference says: The constant pattern is an alternative syntax for == when the right operand is a constant. For strings, the equality operators reference says: String equality comparisons are case-sensitive ordinal comparisons. That's why "Large" doesn't match case "large":. ToLowerInvariant Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture, so the fix compares a lowercase copy and leaves size as it was: the output still printed Large with a capital L.

Can one section run on into the next one?​

Not by itself. The C# guide: Unlike C and Java, C# doesn't allow execution to fall through from one nonempty case section into the next. A case "medium": section with a Console.WriteLine and no break stopped the build with error CS0163: Control cannot fall through from one case label ('case "medium":') to another. When you do want the next section to run, say so with goto case. The C# specification: When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement shall be used. A section for "upsize" that ended with goto case "large"; printed Upsize: one size bigger than regular, then 500 ml.

What happens when no case matches and there's no default?​

Nothing in the switch runs, and the code after it carries on. The C# specification lists the steps a switch takes, and when no label matches and there's no default, its last step applies: Otherwise, control is transferred to the end point of the switch statement. With size set to "huge" and only a case "small": label, nothing inside the switch printed, and the line after it printed After the switch.

Conclusion​

A switch statement runs the section whose case label equals the value, and default catches the rest. End each section with break, stack labels when two values share the same code, and write each label as a constant: text in quotes, or a const. The comparison is case-sensitive, so switch on ToLowerInvariant() when the case of the text can vary.

Additional Resources​