Transitioning from Switch Statements To Switch Expressions in C#

A common feature of many programming languages, including C#, is the switch statement. It provides a concise way to handle multiple conditions within a code block. But as programming languages evolve, new features are added to improve the readability, maintainability, and effectiveness of code. Switch Expressions are one such feature that was added in C# 8.0, which offers a more concise syntax and additional capabilities compared to traditional switch statements.

When was it launched?

Switch Expressions were introduced in C# 8.0, which was released in September 2019. This version of C# brought several new features and enhancements, with switch expressions being one of the most notable additions.

How to use Switch Expressions?

Code is easier to read and write in C# when switch expressions are used instead of switch statements because of their more concise syntax.

Here are some examples showcasing different functionalities of switch expressions.

Simple Example

int day = 3;
string message = day switch
{
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    _ => "Weekend" // Default case using underscore (_)
};

Console.WriteLine(message); // Output: Wednesday

Pattern Matching with Enums

enum TrafficLight { Red, Yellow, Green }

TrafficLight light = TrafficLight.Yellow;
string action = light switch
{
    TrafficLight.Red => "Stop",
    TrafficLight.Yellow => "Caution",
    TrafficLight.Green => "Go"
};

Console.WriteLine(action); // Output: Caution

Case Guards for Additional Conditions

int number = 10;
string result = number switch
{
    int n when (n % 2 == 0) => "Even",
    int n => "Odd",
    _ => "Invalid"
};

Console.WriteLine(result); // Output: Even

Returning Values from Switch Expressions

Unlike traditional switch statements, switch expressions themselves don’t directly contain return statements within each case. However, they can still be used to return values in a concise way. Here's how,

Implicit Return

Each case of the switch expression can directly return a value that matches the expected return type of the expression.

Example

int number = 5;
string message = number switch
{
    1 => "One",
    2 => "Two",
    _ => "More than two"
};

Console.WriteLine(message); // Output: More than two (since 5 is not 1 or 2)

Explicit Return with Calculations

You can perform calculations within a case and return the result.

Example

double length = 10;
double pricePerMeter = 5;
double totalPrice = length switch
{
    double l when l > 0 => l * pricePerMeter,
    _ => throw new ArgumentException("Invalid length")
};

Console.WriteLine(totalPrice); // Output: 50

Important points

  • The switch expression’s overall return type needs to be compatible with the types returned by each case.
  • For cases that don’t explicitly return, the compiler will infer the return type based on the other cases.
  • You can use the (discard pattern) to handle cases where no specific value is returned.

Key differences
 

Syntax

  1. Switch Statements: Traditionally, switch statements in C# have a verbose syntax, requiring the use of the case and break keywords for each case and a default case for handling unmatched values.
    switch (variable)
    {
        case value1:
            // statements
            break;
        case value2:
            // statements
            break;
        // more cases
        default:
            // default statements
            break;
    }
  2. Switch Expressions: Switch expressions offer a more concise syntax using the => arrow syntax. They eliminate the need for explicit break statements and allow for a default case using the wildcard.
    variable switch
    {
        value1 => // expression,
        value2 => // expression,
        // more cases
        _ => // default expression
    };

Type Inference

  • Switch Statements: In switch statements, each case must match the type of the switch variable explicitly.
  • Switch Expressions: Switch expressions can infer the type of the switch variable from the cases, reducing redundancy in type declarations.

Use in Lambda Expressions

  • Switch Statements: These cannot be used directly within lambda expressions.
  • Switch Expressions: This can be used within lambda expressions, allowing for more concise code when defining delegates or event handlers.

Compile-Time Checking

  • Switch Statements: Errors in switch statements might only be caught at runtime, leading to potential bugs.
  • Switch Expressions: Switch expressions offer better compile-time checking, helping catch errors early in the development process.

Null Handling

  • Switch Statements: Cannot handle null values directly, requiring additional checks.
  • Switch Expressions: Can handle null values using the wildcard as the default case.

Conclusion

Switch expressions bring simplicity and clarity to your code, making it easier to maintain and understand. As you continue to work with C#, integrating switch expressions will become a natural choice, streamlining your coding process and improving readability."

keep learning!


Similar Articles