C# Interview Question #82

What is pattern matching in C#?

Advanced C# Language Features Mid-Level Intermediate

Quick Interview Answer

Pattern matching allows code to test an object's type, value, shape, or properties and optionally extract information at the same time.

Detailed Explanation

Pattern matching allows code to test an object's type, value, shape, or properties and optionally extract information at the same time.

Modern C# supports type patterns, constant patterns, relational patterns, property patterns, logical patterns, list patterns, and switch expressions.

Pattern matching often produces cleaner code than repeated casts and nested if statements, especially when handling different object types or domain states.

Code Example

object value = 100;

if (value is int number && number > 0)
{
    Console.WriteLine(number);
}

string result = value switch
{
    int n when n > 0 => "Positive integer",
    string s => $"Text: {s}",
    null => "Null",
    _ => "Other"
};