Switch operator in C#

HomeC#

Switch operator in C#

Transparent text overlay
Add clouds to an image creating a brush
Personalize your Windows 11 Desktop

Let’s explore the switch statement in C#, a powerful tool for selecting one of many code blocks to execute based on the value of an expression.

The switch Statement in C#

The switch statement provides a more efficient and readable alternative to a series of if...else if...else statements when comparing a single expression against multiple constant values.

Syntax:

switch (expression)
{
    case constant1:
        // Code to execute if expression == constant1
        break;
    case constant2:
        // Code to execute if expression == constant2
        break;
    // ... more cases ...
    default:
        // Code to execute if no other case matches
        break;
}
  • switch (expression): The expression to be evaluated. It must be a value that can be compared for equality (e.g., integers, characters, strings, enums).
  • case constant1:: A constant value to compare the expression against.
  • break;: Terminates the switch statement after a matching case is executed. It’s crucial to include break (or return, throw, or goto) at the end of each case block to prevent “fall-through” (executing subsequent cases).
  • default:: An optional case that executes if no other case matches the expression.

Detailed Examples:

1. Basic Integer switch:

int dayOfWeek = 3;

switch (dayOfWeek)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    case 5:
        Console.WriteLine("Friday");
        break;
    case 6:
        Console.WriteLine("Saturday");
        break;
    case 7:
        Console.WriteLine("Sunday");
        break;
    default:
        Console.WriteLine("Invalid day");
        break;
}

In this example, “Wednesday” will be printed because dayOfWeek is 3.

2. Character switch:

char grade = 'B';

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent");
        break;
    case 'B':
        Console.WriteLine("Good");
        break;
    case 'C':
        Console.WriteLine("Average");
        break;
    case 'D':
        Console.WriteLine("Below average");
        break;
    case 'F':
        Console.WriteLine("Fail");
        break;
    default:
        Console.WriteLine("Invalid grade");
        break;
}

Here, “Good” will be outputted.

3. String switch:

string fruit = "apple";

switch (fruit)
{
    case "apple":
        Console.WriteLine("A round, edible fruit.");
        break;
    case "banana":
        Console.WriteLine("A long, curved fruit.");
        break;
    case "orange":
        Console.WriteLine("A citrus fruit.");
        break;
    default:
        Console.WriteLine("Unknown fruit.");
        break;
}

This will print “A round, edible fruit.”

4. Enum switch:

enum Color
{
    Red,
    Green,
    Blue
}

Color selectedColor = Color.Green;

switch (selectedColor)
{
    case Color.Red:
        Console.WriteLine("Selected color: Red");
        break;
    case Color.Green:
        Console.WriteLine("Selected color: Green");
        break;
    case Color.Blue:
        Console.WriteLine("Selected color: Blue");
        break;
    default:
        Console.WriteLine("Unknown color.");
        break;
}

Output: “Selected color: Green”

5. Pattern Matching (C# 7.0 and later):

C# 7.0 introduced pattern matching in switch statements, significantly enhancing their capabilities.

  • when clause: Adds conditional logic to a case label.
  • Type patterns: Matches based on the type of the expression.
  • Positional patterns: Matches based on the properties or elements of an object.
object obj = "Hello";

switch (obj)
{
    case string s when s.Length > 5:
        Console.WriteLine("Long string: " + s);
        break;
    case string s:
        Console.WriteLine("Short string: " + s);
        break;
    case int i:
        Console.WriteLine("Integer: " + i);
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}

This example demonstrates the use of when and type patterns.

6. Switch expressions(C# 8.0 and later)

Switch expressions provide a more concise way to write switch statements, especially when returning values.

int number = 2;
string result = number switch
{
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Other" // The discard pattern '_' matches anything.
};

Console.WriteLine(result);

Important Notes:

  • The switch expression must resolve to a constant value at compile time (except for pattern matching).
  • break; is essential to prevent “fall-through” (unless you intentionally want it).
  • The default case is optional but recommended to handle unexpected values.
  • Pattern matching and switch expressions greatly expand the switch statement’s power.

By using the switch statement effectively, you can create cleaner, more readable, and more maintainable code when dealing with multiple conditional branches.

COMMENTS

DISQUS: