Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

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

Tag: Pattern Matching

C#

C#: Fix a Switch Expression Silently Taking the Wrong Branch Because Two Overlapping Patterns Are Tried in Source Order and the First Match Wins

- 13.11.26 - ErcanOPAK comment on C#: Fix a Switch Expression Silently Taking the Wrong Branch Because Two Overlapping Patterns Are Tried in Source Order and the First Match Wins

🔧 C#: Fix a Switch Expression Silently Taking the Wrong Branch Because Two Overlapping Patterns Are Tried in Source Order and the First Match Wins A switch expression evaluates its arms strictly in the order they’re written and commits to the very first pattern that matches, with no attempt to find the most specific one […]

Read More
C#

C#: Why Pattern Matching Against a Null Object Doesn’t Throw, and Why That’s Not Always Safe

- 03.10.26 - ErcanOPAK comment on C#: Why Pattern Matching Against a Null Object Doesn’t Throw, and Why That’s Not Always Safe

🔧 The Null Check That Was Secretly a Pattern Match All Along Switch expressions and is-pattern checks in modern C# handle null gracefully by design – matching null against a type pattern simply fails to match rather than throwing, which is exactly why ‘if (value is Customer c)’ is safe to write even when value […]

Read More
C#

C#: Fix a Switch Expression That Silently Matches the Wrong Case Because of Pattern Order

- 05.09.26 - ErcanOPAK comment on C#: Fix a Switch Expression That Silently Matches the Wrong Case Because of Pattern Order

🔧 The Cases Look Right – The Wrong One Keeps Matching First A switch expression with pattern matching compiles cleanly and, at runtime, consistently lands on a case that looks like it should never apply before the more specific case underneath it – because pattern order, not just pattern content, decides which branch actually wins. […]

Read More
C#

C#: Write Cleaner Code with Pattern Matching

- 25.07.26 - ErcanOPAK comment on C#: Write Cleaner Code with Pattern Matching

🎯 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 […]

Read More
C#

C#: Use Pattern Matching for Elegant Code

- 07.07.26 - ErcanOPAK comment on C#: Use Pattern Matching for Elegant Code

🎯 Pattern Matching = Elegant Code If-else chains are messy. Pattern matching is elegant. Switch expressions, type matching, property patterns. ❌ If-Else Chains if (obj is string) { … } else if (obj is int) { … } else if (obj is bool) { … } ✅ Pattern Matching switch (obj) { string s => […]

Read More
C#

C#: Use Switch Expressions Instead of Switch Statements

- 07.06.26 - ErcanOPAK comment on C#: Use Switch Expressions Instead of Switch Statements

➡️ switch expression is an expression, not a statement Switch statements are verbose. Switch expressions return values. Less code, fewer bugs, no fall-through. ❌ Switch Statement string GetGrade(int score) { string grade; switch (score) { case >= 90: grade = “A”; break; case >= 80: grade = “B”; break; default: grade = “F”; break; } […]

Read More
C#

C#: Use List Patterns for Powerful Array and List Matching

- 05.06.26 - ErcanOPAK comment on C#: Use List Patterns for Powerful Array and List Matching

📋 Match Arrays Like Prolog Match first element, last element, empty list — all with pattern matching. List patterns make array processing declarative. 📝 Basic Patterns int[] numbers = [1, 2, 3, 4, 5]; // Match first two elements if (numbers is [1, 2, ..]) { Console.WriteLine(“Starts with 1,2”); } // Match last two elements […]

Read More
AI

AI Prompt: Generate Regex Patterns from Examples

- 31.05.26 - ErcanOPAK comment on AI Prompt: Generate Regex Patterns from Examples

🔍 Regular Expressions Are Hard. AI Makes Them Easy. Need to extract emails? Phone numbers? Dates? AI generates regex from examples. No more regex debugging hell. 📝 The Prompt Generate a regular expression that matches: [Provide examples of what you want to match] Example inputs that SHOULD match: – [example 1] – [example 2] – […]

Read More
C#

C#: Use Pattern Matching and Switch Expressions for Cleaner Logic

- 27.05.26 - ErcanOPAK comment on C#: Use Pattern Matching and Switch Expressions for Cleaner Logic

🎯 Replace if-else Chains with Switch Expressions Type checking, property matching, tuple patterns — switch expressions are more readable and less error-prone than long if-else. ❌ Old Way (Verbose) string GetDiscount(User user) { if (user == null) return “0%”; else if (user.Tier == “Gold”) return “20%”; else if (user.Tier == “Silver”) return “10%”; else if […]

Read More
C#

C#: Use Record Types for Immutable Data Objects

- 30.03.26 - ErcanOPAK comment on C#: Use Record Types for Immutable Data Objects

📦 Value Objects Made Easy DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50. Traditional Class vs Record // ❌ Traditional class – Lots of boilerplate public class PersonClass { public string Name { get; init; } public int Age { […]

Read More
C#

C#: Use Pattern Matching for Cleaner Type Checks and Switches

- 22.03.26 - ErcanOPAK comment on C#: Use Pattern Matching for Cleaner Type Checks and Switches

🎯 Switch on Steroids Type casting everywhere? Nested if-else chains? Pattern matching makes type checks and complex conditions elegant. Type Pattern (is) // ❌ Old way: Type check + cast if (obj is string) { string s = (string)obj; Console.WriteLine(s.ToUpper()); } // ✅ Pattern matching: Check and declare in one if (obj is string s) […]

Read More
AI

AI Prompt: Generate Complex Regex Patterns in Plain English

- 19.03.26 - ErcanOPAK comment on AI Prompt: Generate Complex Regex Patterns in Plain English

🔤 Regex Without the Pain Need to validate email? Extract phone numbers? Parse log files? Describe it in English, AI writes the regex. The Regex Prompt Create a regex pattern that matches: [Describe what you want to match] Requirements: – Provide the regex pattern – Explain each part of the pattern – Give 5 examples […]

Read More
C#

C#: Use Pattern Matching with switch Expressions

- 19.03.26 | 19.03.26 - ErcanOPAK comment on C#: Use Pattern Matching with switch Expressions

🎯 Modern Switch Old switch statements verbose. Switch expressions compact, powerful. // Old way string result; switch (value) { case 1: result = “One”; break; case 2: result = “Two”; break; default: result = “Other”; break; } // Modern way var result = value switch { 1 => “One”, 2 => “Two”, _ => “Other” […]

Read More
C#

C#: Simulating Discriminated Unions with Modern Pattern Matching

- 01.03.26 - ErcanOPAK comment on C#: Simulating Discriminated Unions with Modern Pattern Matching

Handle complex business states (Success, Error, Loading) without messy if-else or null checks. public record Result; public record Success(string Data) : Result; public record Failure(int Code) : Result; string message = result switch { Success s => $”Fetched: {s.Data}”, Failure f => $”Error code: {f.Code}”, _ => “Unknown State” };

Read More
AI

AI Prompt: Create Regex Patterns with Explanations

- 22.02.26 - ErcanOPAK comment on AI Prompt: Create Regex Patterns with Explanations

Regex is cryptic. AI writes and explains patterns in plain English. The Prompt: Create a regex pattern for: [Describe what you want to match – e.g., “email addresses”, “phone numbers in format (XXX) XXX-XXXX”, “URLs with optional protocol”] Requirements: – Pattern for [language/tool – e.g., JavaScript, Python, grep] – Explain what each part means – […]

Read More
C#

C#: Use Discard Pattern to Ignore Unwanted Values

- 16.02.26 - ErcanOPAK comment on C#: Use Discard Pattern to Ignore Unwanted Values

Variables you’ll never use clutter code. Discards (_) explicitly mark them as unused. Tuple Deconstruction: // Don’t need middle value var (first, _, last) = (“John”, “middle”, “Doe”); // Don’t need first two var (_, _, important) = GetThreeValues(); Out Parameters: // Only care if it parses, not the value if (int.TryParse(input, out _)) { […]

Read More
C#

C#: Use List Patterns to Match List Elements in Pattern Matching

- 15.02.26 - ErcanOPAK comment on C#: Use List Patterns to Match List Elements in Pattern Matching

Checking list contents with if statements is verbose. C# 11 list patterns make it clean. Traditional Way: if (numbers.Count >= 3 && numbers[0] == 1 && numbers[2] == 3) { // Do something } List Pattern: if (numbers is [1, _, 3, ..]) { // Matches list starting with 1, any value, then 3, then […]

Read More
C#

C#: Use Pattern Matching in Property Patterns for Complex Conditions

- 15.02.26 - ErcanOPAK comment on C#: Use Pattern Matching in Property Patterns for Complex Conditions

Nested if statements for object properties are messy. Property patterns make complex checks clean. Messy If-Else: if (user != null && user.Address != null && user.Address.Country == “USA” && user.Age >= 18) { return “Eligible”; } Clean Property Pattern: var result = user switch { { Address.Country: “USA”, Age: >= 18 } => “Eligible”, { […]

Read More
C#

C#: Use var Pattern in Switch Expressions for Type Matching

- 14.02.26 - ErcanOPAK comment on C#: Use var Pattern in Switch Expressions for Type Matching

Checking object types with multiple if-else is messy. Switch expressions with type patterns are cleaner. Old If-Else Chain: object obj = GetData(); if (obj is string s) { Console.WriteLine($”String: {s.Length} chars”); } else if (obj is int i) { Console.WriteLine($”Number: {i * 2}”); } else if (obj is List list) { Console.WriteLine($”List: {list.Count} items”); } […]

Read More
AI

AI Prompt: Generate Regex Patterns with Explanation and Test Cases

- 13.02.26 - ErcanOPAK comment on AI Prompt: Generate Regex Patterns with Explanation and Test Cases

Struggling with regex syntax? AI writes the pattern and explains how it works. The Prompt: Create a regex pattern that matches: – US phone numbers in formats: (555) 123-4567, 555-123-4567, 5551234567 Provide: 1. The regex pattern 2. Explanation of each part 3. 5 test cases (3 valid, 2 invalid) 4. Code example in JavaScript AI […]

Read More
C#

C#: Use Record Types with With-Expressions for Immutable Data Transformations

- 03.02.26 - ErcanOPAK comment on C#: Use Record Types with With-Expressions for Immutable Data Transformations

Modifying objects causes bugs when multiple parts of code reference the same instance. Records with with-expressions create modified copies safely. The Mutable Class Problem: public class Person { public string Name { get; set; } public int Age { get; set; } } var person = new Person { Name = “John”, Age = 30 […]

Read More
C#

C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions

- 01.02.26 - ErcanOPAK comment on C# Pattern Matching: Replace Complex If-Else Chains with Switch Expressions

Nested if-else statements making your code unreadable? C# 9+ switch expressions with pattern matching can reduce 50+ lines to 10. The Old Nightmare: public decimal CalculateDiscount(Customer customer, Order order) { if (customer == null) return 0; if (customer.IsPremium) { if (order.Total > 1000) return order.Total * 0.20m; else if (order.Total > 500) return order.Total * […]

Read More
November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

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

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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