LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

Pattern Matching in Modern C#

Pattern matching allows us to check a value against a particular condition or type and execute code based on the result.

1What Is Pattern Matching in C#?

Hi friends! Today we will learn about Pattern Matching in modern C#. Pattern matching allows us to check a value against a particular condition or type and execute code based on the result.

Instead of writing multiple if-else conditions and explicit type checks, we can write cleaner and more readable code using patterns.

Modern C# provides features like type patterns, constant patterns, relational patterns, property patterns and switch expressions.

2Think About an Online Shopping App

Imagine an online shopping application. We receive orders with different payment statuses.

If an order is Pending, we show a waiting message. If it is Paid, we confirm the order. If the amount is above ₹5,000, we provide priority processing.

We can handle these conditions using pattern matching instead of writing lengthy if-else statements.

Remember Pattern matching checks values, types and conditions directly inside expressions.

3Explore the Important Patterns

1. Constant Pattern

Checks whether a value matches a constant such as a number, string or enum value.

2. Type Pattern

Checks whether an object belongs to a particular type. It can also declare a variable of that type.

3. Relational Pattern

Checks conditions using operators such as greater than, less than and equal to.

4. Property Pattern

Checks an object's properties against specified values or conditions.

5. Switch Expression

Returns a value based on matching conditions. It provides a concise alternative to traditional switch statements.

Pattern Purpose
Constant Match an exact value
Type Match an object type
Relational Compare numeric values
Property Check object properties
Switch expression Return a value based on patterns
Pro Tip Use switch expressions when multiple conditions need to return different values.
Common Mistake Pattern order matters. Place more specific patterns before general patterns to avoid unreachable cases.

4Let's Build an Order Processing Program

Let's create an order class and use different patterns to identify the order status and priority.

Program.cs
using System;

class Order
{
    public string Status { get; set; }
    public double Amount { get; set; }
}

class Program
{
    static string GetStatus(Order order) =>
        order.Status switch
        {
            "Paid" => "Order confirmed",
            "Pending" => "Waiting for payment",
            _ => "Unknown status"
        };

    static void Main()
    {
        Order order = new Order
        {
            Status = "Paid",
            Amount = 6000
        };

        Console.WriteLine(GetStatus(order));

        string priority = order.Amount switch
        {
            > 5000 => "Priority processing",
            > 0 => "Normal processing",
            _ => "Invalid amount"
        };

        Console.WriteLine(priority);

        object payment = "UPI";

        if (payment is string method)
            Console.WriteLine(method);
    }
}

Here we use a switch expression for payment status, relational patterns for order amount and a type pattern to identify the payment method.

5Check the Application Result

Output
Order confirmed
Priority processing
UPI

The order is Paid, so it is confirmed. The amount is greater than 5,000, so priority processing is selected. Finally, the type pattern identifies the payment value as a string.

6Watch Pattern Matching in VS Code

Follow how C# evaluates the order status, amount and payment type.

Program.cs - Visual Studio Code
● Program.cs   C#
◫⌕⑂⚙
1static string GetStatus(Order order) =>
2 order.Status switch
3 {
4 "Paid" => "Order confirmed",
5 "Pending" => "Waiting for payment",
6 _ => "Unknown status"
7 };
8string priority = order.Amount switch
9{
10 > 5000 => "Priority processing",
11 > 0 => "Normal processing",
12 _ => "Invalid amount"
13};
14if (payment is string method)
15 Console.WriteLine(method);
PROBLEMSOUTPUTDEBUG CONSOLETERMINAL
PS C:\Projects\Demo> dotnet run
Evaluating order...
C#UTF-8   CRLF   C#

7What Should You Remember?

Pattern matching makes conditional logic cleaner and easier to maintain. It supports checking values, types, properties and ranges.

  • Use constant and type patterns to match values and types.
  • Use relational and property patterns for conditions.
  • Use switch expressions to return values cleanly.

8Questions Interviewers Love to Ask

Q1Easy

What is pattern matching in C#?

Answer: It checks whether a value matches a particular pattern, such as a type, constant, property or relational condition.

Q2Easy

What is a type pattern?

Answer: A type pattern checks whether an object matches a specified type and can declare a variable of that type.

Q3Medium

What is the difference between switch statement and switch expression?

Answer: A switch statement executes code for matching cases. A switch expression evaluates patterns and returns a value.

Q4Medium

What are relational patterns?

Answer: They compare values using operators such as greater than, less than, greater than or equal to, and less than or equal to.

Q5Hard

What is a property pattern?

Answer: It checks one or more properties of an object. For example, order is { Status: "Paid", Amount: > 5000 }.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.