What Is Pattern Matching?

What Is Pattern Matching?

Imagine you’re organizing a Halloween party. You put pumpkins by the door, costumes in one room, and candy on the snack table. Suddenly, someone brings in something unusual—a baseball cap! You think, “Hmm, that’s not Halloween-y,” and toss it into the “random stuff” bin. In C#, Pattern Matching is like having a helper who does this kind of sorting for your code! It helps your program understand what each item is and what to do with it, making everything simpler and easier to manage.

How Does It Work?

In C#, Pattern Matching acts like a Halloween item sorter:

  1. Identifies the type of an item (whether it's a pumpkin, a candy, or a decoration).
  2. Breaks down items into parts: Like asking, “Is this candy extra special?” or “Is this pumpkin huge?”
  3. Applies filters: You can add conditions like “only chocolate candy” or “only spooky decorations.”

Let’s see how this works in a fun example.

Simplifying Decisions with switch and Pattern Matching

Imagine you have a bunch of Halloween items to sort. Depending on what each item is, you have different plans:

  • If it’s a pumpkin, you put it by the entrance.
  • If it’s a special candy, it goes on the fancy table.
  • If it’s regular candy, it goes on the snack table.
  • If it’s a decoration, you hang it on the wall.

With Pattern Matching, switch can handle all this easily:

public void HandleHalloweenItem(object item)
{
    switch (item)
    {
        case Pumpkin pumpkin:
            Console.WriteLine("Placing pumpkin by the entrance.");
            break;

        case Candy candy when candy.IsSpecial:
            Console.WriteLine($"Putting special candy {candy.Name} on the fancy table!");
            break;

        case Candy candy:
            Console.WriteLine($"Putting regular candy {candy.Name} on the snack table.");
            break;

        case Decoration decor:
            Console.WriteLine("Hanging decoration on the wall.");
            break;

        case null:
            Console.WriteLine("No item to handle.");
            break;

        default:
            Console.WriteLine("Unknown item. Ignoring it.");
            break;
    }
}        

Here’s what this switch does at the Halloween party:

  1. Pumpkin: If the item is a pumpkin, it goes right by the door.
  2. Special Candy: It’s a VIP candy, so it gets the fancy table.
  3. Regular Candy: Just another treat; it goes on the snack table.
  4. Decoration: It’s time to decorate!
  5. Miscellaneous: If it’s anything else, we’ll ignore it.

Using Pattern Matching with if

Pattern Matching also works with if statements, which can make things even simpler:

if (item is Pumpkin)
{
    Console.WriteLine("Placing pumpkin by the entrance.");
}
else if (item is Candy candy && candy.IsSpecial)
{
    Console.WriteLine($"Putting special candy {candy.Name} on the fancy table.");
}
else if (item is Candy candy)
{
    Console.WriteLine($"Putting regular candy {candy.Name} on the snack table.");
}
else if (item is Decoration)
{
    Console.WriteLine("Hanging decoration on the wall.");
}
else
{
    Console.WriteLine("Unknown item. Ignoring it.");
}        

With if, Pattern Matching still identifies each item type and takes the right action—a real time-saver!

Why Use Pattern Matching?

  1. Makes code clearer: It’s like a list of party rules that everyone can easily follow.
  2. All in one place: No need for lots of type-checking or converting—Pattern Matching handles it in one spot.
  3. Powerful combinations: when conditions let you match types and apply rules at the same time.

Wrapping Up

Pattern Matching in C# is like having a Halloween party assistant who knows exactly what to do with pumpkins, candy, and decorations without you having to keep explaining. It keeps your code organized and is an awesome way to simplify complex conditions.

How about you? Have you tried Pattern Matching? Share how it helps keep your code cleaner and clearer!

Rafael Andrade

Data Engineer | Azure | AWS | Databricks | Snowflake | Apache Spark | Python | PySpark

3 周

Informative post! Thanks for sharing, Cássio Huggentobler de Costa.

回复
Gustavo Guedes

Senior Flutter Developer | iOS Developer | Mobile Developer | Flutter | Swift | UIKit | SwiftUI

3 周

Very helpful Cássio Huggentobler de Costa! Thanks for sharing.

回复
Erick Zanetti

Fullstack Engineer | Software Developer | React | Next.js | TypeScript | Node.js | JavaScript | AWS

3 周

Very informative

回复
André Ramos

Senior Fullstack Software Developer | Java | Angular | React | Tech Lead

3 周

Nice to see the Pattern Matching in your post of C#. I wrote this same topic and theme, but for Java. Are we synchronized ? kkkk Congratulations, really good article.

回复
Kléber Allmeida

Manager Solutions Architecture | Machine Learning Engineer | Golang | Kotlin | Flutter | React Native | Angular | Figma | Java | .Net | Nodejs | DevOps | Maven | JUnit | CI/CD | GitHub | Design Patterns | Multi Cloud

3 周

Very informative

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了