Bird
Raised Fist0
C Sharp (C#)programming~7 mins

Pattern matching in switch in C Sharp (C#)

Choose your learning style10 modes available
Introduction

Pattern matching in switch helps you check a value against different shapes or types easily. It makes your code cleaner and easier to read.

You want to run different code depending on the type of an object.
You want to check if a value fits a certain pattern or condition inside a switch.
You want to simplify complex if-else chains by using switch with patterns.
You want to extract parts of a value while checking its type.
You want to handle different cases clearly in one place.
Syntax
C Sharp (C#)
switch (variable)
{
    case TypeName variableName:
        // code when variable is TypeName
        break;
    case TypeName { Property: value } variableName:
        // code when variable matches pattern with property
        break;
    case int number when number > 0:
        // code when variable is int and greater than 0
        break;
    case null:
        // code when variable is null
        break;
    default:
        // code for all other cases
        break;
}

You can match types, properties, and add extra conditions with when.

Use default to catch all unmatched cases.

Examples
This checks the type of value and prints a message accordingly.
C Sharp (C#)
object value = 42;
switch (value)
{
    case int number:
        Console.WriteLine($"It's an integer: {number}");
        break;
    case string text:
        Console.WriteLine($"It's a string: {text}");
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}
This matches strings and checks if their length is greater than 3.
C Sharp (C#)
object value = "hello";
switch (value)
{
    case string { Length: > 3 } longText:
        Console.WriteLine($"Long string: {longText}");
        break;
    case string shortText:
        Console.WriteLine($"Short string: {shortText}");
        break;
    default:
        Console.WriteLine("Not a string");
        break;
}
This handles the case when the value is null.
C Sharp (C#)
object value = null;
switch (value)
{
    case null:
        Console.WriteLine("Value is null");
        break;
    default:
        Console.WriteLine("Value is not null");
        break;
}
Sample Program

This program shows how to use pattern matching in a switch to handle different types and conditions. It prints the items before and after applying the switch with patterns.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        object[] items = { 10, "hello", 3.14, null, "hi" };

        Console.WriteLine("Before switch pattern matching:");
        foreach (var item in items)
        {
            Console.WriteLine(item ?? "null");
        }

        Console.WriteLine("\nAfter switch pattern matching:");
        foreach (var item in items)
        {
            switch (item)
            {
                case int number when number > 5:
                    Console.WriteLine($"Integer greater than 5: {number}");
                    break;
                case int number:
                    Console.WriteLine($"Integer 5 or less: {number}");
                    break;
                case string { Length: > 3 } longText:
                    Console.WriteLine($"Long string: {longText}");
                    break;
                case string shortText:
                    Console.WriteLine($"Short string: {shortText}");
                    break;
                case null:
                    Console.WriteLine("Null value found");
                    break;
                default:
                    Console.WriteLine($"Other type: {item}");
                    break;
            }
        }
    }
}
OutputSuccess
Important Notes

Time complexity depends on the number of cases but is generally efficient for small sets.

Space complexity is minimal as no extra storage is needed beyond the switch.

Common mistake: forgetting to handle null values can cause runtime errors.

Use pattern matching in switch when you want clear, readable code for multiple type or condition checks instead of many if-else statements.

Summary

Pattern matching in switch lets you check types and conditions clearly.

You can match properties and add extra checks with when.

It helps write cleaner and easier-to-read code than many if-else statements.

Practice

(1/5)
1. What does pattern matching in a switch statement primarily help you do in C#?
easy
A. Check an object's type and properties in a clear way
B. Loop through collections more efficiently
C. Declare variables with less code
D. Handle exceptions automatically

Solution

  1. Step 1: Understand pattern matching purpose

    Pattern matching in switch lets you test an object's type and properties clearly.
  2. Step 2: Compare with other options

    Looping, variable declaration, and exception handling are unrelated to pattern matching in switch.
  3. Final Answer:

    Check an object's type and properties in a clear way -> Option A
  4. Quick Check:

    Pattern matching = type and property checks [OK]
Hint: Pattern matching checks types and conditions clearly [OK]
Common Mistakes:
  • Confusing pattern matching with loops
  • Thinking it handles exceptions
  • Believing it declares variables automatically
2. Which of the following is the correct syntax to match an integer variable num equal to 10 using pattern matching in a switch expression?
easy
A. case int n when n == 10:
B. case int n == 10:
C. case int n => 10:
D. case int n is 10:

Solution

  1. Step 1: Recall correct pattern matching syntax

    To match a value with a condition, use case Type variable when condition:.
  2. Step 2: Check each option

    case int n when n == 10: uses when n == 10, which is correct. Others use invalid syntax.
  3. Final Answer:

    case int n when n == 10: -> Option A
  4. Quick Check:

    Use 'when' for conditions in pattern matching [OK]
Hint: Use 'when' keyword for conditions in switch patterns [OK]
Common Mistakes:
  • Using '==' directly after case without 'when'
  • Using '=>' or 'is' incorrectly in case
  • Omitting the variable name
3. What will be the output of this C# code?
object obj = 42;
switch (obj)
{
    case int n when n > 40:
        Console.WriteLine("Greater than 40");
        break;
    case int n:
        Console.WriteLine("Integer");
        break;
    default:
        Console.WriteLine("Other");
        break;
}
medium
A. Integer
B. Other
C. Greater than 40
D. No output (compile error)

Solution

  1. Step 1: Identify the object type and value

    obj is an integer with value 42.
  2. Step 2: Evaluate switch cases in order

    First case matches int n when n > 40, which is true for 42, so prints "Greater than 40" and breaks.
  3. Final Answer:

    Greater than 40 -> Option C
  4. Quick Check:

    Pattern with 'when' matched first [OK]
Hint: Check cases top to bottom; first match runs [OK]
Common Mistakes:
  • Ignoring the 'when' condition
  • Assuming second case runs first
  • Thinking default runs for int
4. Identify the error in this switch statement using pattern matching:
object val = "hello";
switch (val)
{
    case string s when s.Length > 3
        Console.WriteLine("Long string");
        break;
    default:
        Console.WriteLine("Other");
        break;
}
medium
A. Cannot use 'when' with string type
B. Missing colon ':' after case pattern
C. Missing parentheses around condition
D. Incorrect variable name in case

Solution

  1. Step 1: Check switch case syntax

    Each case pattern must end with a colon ':' before the statements.
  2. Step 2: Locate missing colon

    The case line lacks ':' after when s.Length > 3, causing syntax error.
  3. Final Answer:

    Missing colon ':' after case pattern -> Option B
  4. Quick Check:

    Case patterns need ':' after condition [OK]
Hint: Always put ':' after case pattern line [OK]
Common Mistakes:
  • Forgetting ':' after case pattern
  • Adding parentheses around 'when' condition
  • Thinking 'when' can't be used with strings
5. Given a list of objects items containing integers and strings, how would you use pattern matching in a switch expression to return a new list of strings where:
- Integers greater than 10 become "Big number"
- Strings longer than 5 characters become "Long text"
- All others become "Other"?

Which code snippet correctly implements this?
hard
A. items.Select(item => item switch { int n when n > 10: "Big number", string s when s.Length > 5: "Long text", _ => "Other" }).ToList();
B. items.Select(item => switch (item) { case int n if n > 10: "Big number"; case string s if s.Length > 5: "Long text"; default: "Other"; }).ToList();
C. items.Select(item => item switch { int n if n > 10: "Big number", string s if s.Length > 5: "Long text", _ => "Other" }).ToList();
D. items.Select(item => item switch { int n when n > 10 => "Big number", string s when s.Length > 5 => "Long text", _ => "Other" }).ToList();

Solution

  1. Step 1: Understand switch expression syntax

    Switch expressions use '=>' for cases, and 'when' for conditions.
  2. Step 2: Check each option's syntax

    items.Select(item => item switch { int n when n > 10 => "Big number", string s when s.Length > 5 => "Long text", _ => "Other" }).ToList(); uses correct 'item switch { case => result }' with 'when' and '=>'. Other options use invalid syntax ('switch' inside lambda or 'if' instead of 'when'). items.Select(item => item switch { int n when n > 10: "Big number", string s when s.Length > 5: "Long text", _ => "Other" }).ToList(); uses ':' instead of '=>', which is invalid in switch expressions.
  3. Final Answer:

    items.Select(item => item switch { int n when n > 10 => "Big number", string s when s.Length > 5 => "Long text", _ => "Other" }).ToList(); -> Option D
  4. Quick Check:

    Switch expressions use '=>' and 'when' [OK]
Hint: Use '=>' and 'when' in switch expressions for conditions [OK]
Common Mistakes:
  • Using ':' instead of '=>' in switch expressions
  • Using 'if' instead of 'when' for conditions
  • Trying to put 'switch' keyword inside lambda
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard