🔧 Your Nullable Comparison Is Quietly Excluding Every Null Row
A LINQ filter compares a nullable int against a threshold – `x > 5` – and it looks correct, until you notice every row where the value is null just vanished from the results instead of showing up as unmatched the way you expected, because in C# any comparison against null with a relational operator evaluates to false, never to null.
🔎 The Problem
public class Order
{
public int Id { get; set; }
public int? DiscountPercent { get; set; } // nullable - not every order has one
}
var highDiscountOrders = orders.Where(o => o.DiscountPercent > 20).ToList();
// An order with DiscountPercent == null is silently excluded here -
// (null > 20) evaluates to false, not "unknown" - there's no exception,
// no warning, just a result set that's missing rows you may have expected
// to see flagged as "needs review" instead of dropped entirely.
✅ Fix: Decide Explicitly What Null Should Mean
- If null should count as “below threshold”, the code above is already doing the right thing – but say so explicitly with `o.DiscountPercent.GetValueOrDefault() > 20` or `(o.DiscountPercent ?? 0) > 20` so the next reader doesn’t have to know the null-comparison rule to understand intent.
- If null should be treated as its own separate case (e.g., “pending” or “needs review”), filter for it explicitly: `o.DiscountPercent == null || o.DiscountPercent > 20`, or branch the two cases into separate lists entirely.
⚠️ The Rule to Remember
- For nullable value types, `==` and `!=` treat null as a normal comparable value (`null == null` is true), but `<`, `>`, `<=`, `>=` all return false whenever either side is null – there is no three-valued logic here like in SQL’s `NULL` handling.
- This asymmetry is exactly why a filter that reads correctly at a glance can silently drop rows – the bug is in what you didn’t consider, not in what the compiler let you write.
Null isn’t a value below zero – it’s the absence of one, and a `>` comparison that quietly treats it as “loses” is a decision, even when nobody made it on purpose.
