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#: Why Pattern Matching Against a Null Object Doesn’t Throw, and Why That’s Not Always Safe

- 03.10.26 - ErcanOPAK

🔧 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 is null, and why a switch expression with a null case reads cleanly. The part that catches experienced developers off guard is relying on that same graceful non-throwing behavior as if it were equivalent to an explicit null check everywhere, when a pattern that looks like it covers ‘anything else’ doesn’t always cover null the way a plain default case nor an unconstrained discard pattern might silently suggest it does.

🔎 The Problem

public decimal GetDiscount(Customer? customer) => customer switch
{
    PremiumCustomer p => p.Rate,
    StandardCustomer s => s.Rate,
    _ => 0.05m // looks like it covers "everything else" including null -
               // and it DOES, which is actually the trap: a genuinely
               // unexpected null silently gets the default discount
               // instead of surfacing as the bug it probably is.
};

// Call site, months later:
var discount = GetDiscount(LookupCustomerOrNull(id)); // returns null when the
                                                        // id was deleted - and
                                                        // nobody notices, since
                                                        // 0.05m is a perfectly
                                                        // plausible-looking value.

✅ Fix: Decide Deliberately Whether Null Deserves Its Own Case

  • Adding an explicit null pattern as its own switch arm (null => throw new ArgumentNullException(…), placed before the discard) forces a genuinely unexpected null to fail loudly and immediately, rather than quietly falling into whatever the catch-all case happens to return.
  • Making the parameter type non-nullable (Customer instead of Customer?) wherever null genuinely should never be a valid input shifts the responsibility to the caller and to nullable-reference-type warnings at compile time, rather than to a runtime switch expression that has to decide what to do about it.
  • Reviewing every discard pattern (_) in a switch over a reference type specifically for whether it’s meant to include null is worth doing once per switch, since the discard pattern matching null is easy to intend and easy to forget having intended.

⚠️ Why the Language Behaves This Way on Purpose

  • Making pattern matching null-safe by default (rather than throwing a NullReferenceException on every null input) is a deliberate design choice that makes null-conditional logic easier to write correctly in the common case – the cost is that it also makes it easy to handle null exactly the same as any other unmatched value without noticing.
  • This is most dangerous specifically in catch-all arms that return a plausible default value rather than an obviously-wrong one (0, empty string, false) – an obviously wrong default gets noticed quickly, while a plausible one can hide a real null for a long time.

A pattern match that doesn’t throw on null isn’t the same as a pattern match that handles null correctly – it just means the mistake won’t be the one that gets you a stack trace.

— C# Best Practice

Related posts:

C# Exception Handling — The Silent Performance Killer

The Hidden Cost of record Types in Hot Paths

C#: Advanced LINQ Query Patterns for Complex Data

Post Views: 3

Post navigation

HTML5: Fix a Form That Submits on Enter From One Input but Not Another
Git: Fix a Merge That Reports Already Up to Date When Your Branch Clearly Isn’t

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 (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)
  • 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 (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)

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