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

Switch expressions with patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Switch expressions with patterns let you choose a result based on the shape or value of data in a clear and simple way.

You want to return different results based on the type of an object.
You need to check if a value fits certain conditions and respond accordingly.
You want to replace long if-else chains with cleaner code.
You want to match values and extract parts of data easily.
Syntax
C Sharp (C#)
var result = value switch
{
    pattern1 => expression1,
    pattern2 => expression2,
    _ => defaultExpression
};

The switch expression evaluates value against each pattern in order.

The underscore _ is a catch-all pattern for anything not matched before.

Examples
This matches exact numbers and returns a string for each case.
C Sharp (C#)
int number = 5;
string result = number switch
{
    1 => "One",
    2 => "Two",
    _ => "Other"
};
This matches the type of obj and extracts the value.
C Sharp (C#)
object obj = "hello";
string result = obj switch
{
    int i => $"Number {i}",
    string s => $"Text '{s}'",
    _ => "Unknown"
};
This uses relational patterns to check ranges.
C Sharp (C#)
int age = 20;
string category = age switch
{
    < 13 => "Child",
    >= 13 and < 20 => "Teen",
    _ => "Adult"
};
Sample Program

This program checks each item in an array and prints a description based on its type or value.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        object[] items = { 42, "apple", 3.14, null };

        foreach (var item in items)
        {
            string description = item switch
            {
                int i => $"Integer: {i}",
                string s => $"String: '{s}'",
                null => "Null value",
                _ => "Other type"
            };
            Console.WriteLine(description);
        }
    }
}
OutputSuccess
Important Notes

Switch expressions are expressions, so they return a value directly.

Patterns can be combined with and, or, and not for more complex checks.

Always include a catch-all _ pattern to handle unexpected cases.

Summary

Switch expressions with patterns let you match values and types cleanly.

They help replace long if-else chains with clearer code.

Patterns can check types, values, and conditions easily.