0
0
C Sharp (C#)programming~5 mins

Switch expression (modern C#)

Choose your learning style9 modes available
Introduction

A switch expression helps you choose a value based on different cases in a simple and clear way.

When you want to pick a result based on different options.
When you want cleaner code instead of many if-else statements.
When you want to return a value directly from multiple conditions.
When you want to handle different inputs with clear, readable code.
Syntax
C Sharp (C#)
var result = input switch
{
    case1 => value1,
    case2 => value2,
    _ => defaultValue
};

The switch expression returns a value directly.

The underscore _ means 'anything else' (default case).

Examples
This example checks the day and returns if it is a weekend or a weekday.
C Sharp (C#)
var dayType = dayOfWeek switch
{
    "Saturday" => "Weekend",
    "Sunday" => "Weekend",
    _ => "Weekday"
};
This example converts a number to its word form or returns 'Unknown' if not matched.
C Sharp (C#)
int number = 3;
string word = number switch
{
    1 => "One",
    2 => "Two",
    3 => "Three",
    _ => "Unknown"
};
Sample Program

This program uses a switch expression to find the color of a fruit and prints it.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        string fruit = "Apple";
        string color = fruit switch
        {
            "Apple" => "Red",
            "Banana" => "Yellow",
            "Grape" => "Purple",
            _ => "Unknown color"
        };
        Console.WriteLine($"The color of {fruit} is {color}.");
    }
}
OutputSuccess
Important Notes

Switch expressions are more concise than traditional switch statements.

Always include a default case using _ to handle unexpected values.

Switch expressions can be used anywhere an expression is allowed.

Summary

Switch expressions let you pick a value based on cases in a simple way.

Use _ as a default to catch all other cases.

They make your code shorter and easier to read compared to many if-else statements.