Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Write Cleaner Code with Pattern Matching

- 25.07.26 - ErcanOPAK

🎯 Pattern Matching = Cleaner Code

Complex conditionals are hard to read. Pattern matching makes code more expressive and maintainable.

📝 Pattern Matching Basics

// Type Patterns
public void ProcessShape(object shape)
{
    if (shape is Circle circle)
    {
        Console.WriteLine($"Circle with radius {circle.Radius}");
    }
    else if (shape is Rectangle rect)
    {
        Console.WriteLine($"Rectangle {rect.Width}x{rect.Height}");
    }
    else if (shape is Triangle tri)
    {
        Console.WriteLine($"Triangle with sides {tri.SideA}, {tri.SideB}, {tri.SideC}");
    }
}

// Switch Expression (C# 8+)
public string GetShapeInfo(object shape) => shape switch
{
    Circle { Radius: > 10 } => "Large circle",
    Circle { Radius: > 5 } => "Medium circle",
    Circle { Radius: <= 5 } => "Small circle",
    Rectangle { Width: var w, Height: var h } when w == h => $"Square ({w}x{h})",
    Rectangle { Width: var w, Height: var h } => $"Rectangle ({w}x{h})",
    Triangle { SideA: var a, SideB: var b, SideC: var c } => $"Triangle ({a},{b},{c})",
    null => "Null object",
    _ => "Unknown shape"
};

// Property Patterns
public bool IsValidUser(User user) => user is
{
    Age: > 18,
    Email: not null,
    Status: UserStatus.Active
};

🎯 Advanced Pattern Matching

// Tuple Patterns
public string EvaluateState(bool isActive, bool isVerified) => (isActive, isVerified) switch
{
    (true, true) => "Fully active",
    (true, false) => "Active but unverified",
    (false, true) => "Verified but inactive",
    (false, false) => "Inactive and unverified"
};

// Relational Patterns (C# 9+)
public string GetTemperatureCategory(int temperature) => temperature switch
{
    < 0 => "Freezing",
    < 10 => "Cold",
    < 20 => "Cool",
    < 30 => "Warm",
    < 40 => "Hot",
    >= 40 => "Very hot"
};

// Logical Patterns
public string GetStudentGrade(int score) => score switch
{
    >= 90 and <= 100 => "A",
    >= 80 and < 90 => "B",
    >= 70 and < 80 => "C",
    >= 60 and < 70 => "D",
    < 60 => "F",
    _ => "Invalid score"
};

// Positional Patterns
public record Point(int X, int Y);

public string DescribePoint(Point point) => point switch
{
    (0, 0) => "Origin",
    (var x, 0) => $"On X-axis at {x}",
    (0, var y) => $"On Y-axis at {y}",
    (var x, var y) when x == y => $"On diagonal at ({x},{y})",
    (var x, var y) => $"At ({x},{y})"
};

// List Patterns (C# 11+)
public string DescribeNumbers(int[] numbers) => numbers switch
{
    [] => "Empty array",
    [1] => "Single item: 1",
    [1, 2] => "Exactly [1, 2]",
    [1, ..] => "Starts with 1",
    [_, _, 3] => "Ends with 3",
    [var first, var second, ..] => $"First two: {first}, {second}",
    _ => "Other array"
};

💡 Pattern Matching Tips

  • Use switch expressions for concise logic
  • Combine with property patterns
  • Use when clauses for complex conditions
  • Handle all cases in switch expressions
  • Use patterns for validation

Pattern matching makes C# code more declarative and readable. It reduces boilerplate and eliminates common bugs.

— Software Engineer

Related posts:

C# Async/Await: Deep Dive into the Most Important Feature

C#: Use 'yield return' for Memory Efficient Iteration

Why LINQ in Hot Paths Can Kill Performance

Post Views: 4

Post navigation

C#: Build Immutable Data with Record Types
Visual Studio: Master Test Explorer for Unit Testing

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (939)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (837)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com