0
0
CsharpConceptBeginner · 3 min read

What is Pattern Matching in C#: Simple Explanation and Examples

In C#, pattern matching is a feature that lets you check an object's type or shape and extract data from it in a clear and concise way. It helps write cleaner code by combining type checks and casts into simple expressions.
⚙️

How It Works

Pattern matching in C# works like a smart filter that looks at an object and decides if it fits a certain shape or type. Imagine sorting mail: instead of opening every envelope fully, you just check the address to decide where it goes. Similarly, pattern matching checks if an object matches a pattern, such as being a certain type or having specific properties.

When a pattern matches, you can also pull out parts of the object directly, like taking out the recipient's name from the envelope without opening it fully. This makes your code shorter and easier to read because you don’t need separate steps to check the type and then extract data.

💻

Example

This example shows how pattern matching checks an object's type and extracts data in one step.

csharp
object obj = "Hello, world!";

if (obj is string text)
{
    Console.WriteLine($"The text is: {text}");
}
else
{
    Console.WriteLine("Not a string.");
}
Output
The text is: Hello, world!
🎯

When to Use

Use pattern matching when you need to check an object's type or structure and want to write clear, concise code. It is especially helpful in switch statements or if conditions where you handle different types differently.

For example, in programs that process different shapes, messages, or data formats, pattern matching lets you easily separate logic based on the object's form without extra casting or verbose code.

Key Points

  • Pattern matching combines type checking and data extraction in one step.
  • It makes code easier to read and less error-prone.
  • Commonly used with is expressions and switch statements.
  • Introduced in C# 7.0 and improved in later versions.

Key Takeaways

Pattern matching simplifies type checks and data extraction in C#.
It helps write cleaner and more readable conditional code.
Use it in if statements and switch cases to handle different types easily.
It reduces the need for explicit casting and nested conditions.