DEV Community

Cover image for ๐Ÿ”Ÿ Real Problems You Can Fix with C# Pattern Matching
davinceleecode
davinceleecode Subscriber

Posted on

๐Ÿ”Ÿ Real Problems You Can Fix with C# Pattern Matching

C# pattern matching (introduced in C# 7.0 and enhanced in later versions) simplifies many everyday coding problems. Here are 10 real-world examples where it makes your code cleaner, safer, and more readable.


1 โŒ The Classic Null Check Issue
Old Way:

if (obj != null && obj is Customer)
{
    var customer = (Customer)obj;
}
Enter fullscreen mode Exit fullscreen mode

New Way (Type Pattern - C# 7.0):

if (obj is Customer customer)
{
    // No need for explicit type casting
}
Enter fullscreen mode Exit fullscreen mode

2 ๐Ÿ”„ switch Case Logic
Old Way:

switch (fruit)
{
    case "Apple":
        Console.WriteLine("Red");
        break;
    case "Banana":
        Console.WriteLine("Yellow");
        break;
}

Enter fullscreen mode Exit fullscreen mode

New Way (Switch Expression):

var color = fruit switch
{
    "Apple" => "Red",
    "Banana" => "Yellow",
    _ => "Unknown"
};
Enter fullscreen mode Exit fullscreen mode

3 ๐Ÿ”ข Enum Value Checks
Old Way:

if (status == Status.Active || status == Status.Pending)
{
    // do something
}
Enter fullscreen mode Exit fullscreen mode

New Way:

if (status is Status.Active or Status.Pending)
{
    // cleaner
}
Enter fullscreen mode Exit fullscreen mode

4 ๐Ÿ” Nested if-else Blocks
Old Way:

if (obj is Employee)
{
    var emp = (Employee)obj;
    if (emp.Department == "HR")
    {
        Console.WriteLine("HR Employee");
    }
}
Enter fullscreen mode Exit fullscreen mode

New Way:

if (obj is Employee { Department: "HR" })
{
    Console.WriteLine("HR Employee");
}
Enter fullscreen mode Exit fullscreen mode

5 ๐Ÿงน Multiple Property Conditions Causing Clutter
Old Way:

if (customer != null && customer.Age > 18 && customer.Location == "US")
{
    Console.WriteLine("Valid customer");
}
Enter fullscreen mode Exit fullscreen mode

New Way:

if (customer is { Age: > 18, Location: "US" })
{
    Console.WriteLine("Valid customer");
}
Enter fullscreen mode Exit fullscreen mode

6 ๐Ÿ”ค Overcomplicated String Pattern Matching

if (command == "Start" || command == "Run" || command == "Begin")
{
    Console.WriteLine("Executing action...");
}
else if (command == "Stop" || command == "End" || command == "Terminate")
{
    Console.WriteLine("Stopping action...");
}
Enter fullscreen mode Exit fullscreen mode

New Way:

var commandResult = command switch
{
    "Start" or "Run" or "Begin" => "Executing action...",
    "Stop" or "End" or "Terminate" => "Stopping action...",
    _ => "Unknown command"
};
Enter fullscreen mode Exit fullscreen mode

7 ๐Ÿ”ข Complex Number Range Checks
Old Way:

if (score >= 50 && score <= 100)
{
    Console.WriteLine("Valid score range");
}
Enter fullscreen mode Exit fullscreen mode

New Way:

if (score is >= 50 and <= 100)
{
    Console.WriteLine("Valid score range");
}
Enter fullscreen mode Exit fullscreen mode

8 ๐Ÿงฎ Verbose Tuple Checks
Old Way:

if (coordinates.X == 10 && coordinates.Y == 20)
{
    Console.WriteLine("Match found");
}
Enter fullscreen mode Exit fullscreen mode

New Way:

if (coordinates is (10, 20))
{
    Console.WriteLine("Match found");
}

Enter fullscreen mode Exit fullscreen mode

9 โœ… Boolean Flag Checks Requiring Extra Logic
Old Way:

if (isActive && isVerified)
{
    Console.WriteLine("User has access.");
}
else if (!isActive || !isVerified)
{
    Console.WriteLine("Access denied.");
}
Enter fullscreen mode Exit fullscreen mode

New Way:

var result = (isActive, isVerified) switch
{
    (true, true) => "User has access.",
    (false, _) or (_, false) => "Access denied."
};

Console.WriteLine(result);
Enter fullscreen mode Exit fullscreen mode

10 ๐Ÿ” Checking for Multiple Values in an Array
Old Way:

int[] validValues = { 10, 20, 30 };
if (validValues.Contains(value))
{
    Console.WriteLine("Value is valid");
}
Enter fullscreen mode Exit fullscreen mode

New Way (List Pattern Matching - C# 11+):

if (validValues is [_, >= 20, 30])
{
    Console.WriteLine("Value is valid");
}

Enter fullscreen mode Exit fullscreen mode

If you found this helpful, consider supporting my work at โ˜• Buy Me a Coffee.

Top comments (2)

Collapse
 
shifa_2 profile image
Shifa

such a great article

Collapse
 
davinceleecode profile image
davinceleecode

Thanks @shifa_2 .. Lets learn everyday ๐Ÿ”ฅ

Some comments may only be visible to logged-in visitors. Sign in to view all comments.