C# LINQ NullReferenceException Fix
In this tutorial, you'll learn about C# LINQ NullReferenceException Fix. We cover key concepts, practical examples, and best practices.
Your LINQ query throws NullReferenceException:
var result = customers.Where(c => c.Orders.Any(o => o.Amount > 100));
If customers is null, Where() throws. If any customer.Orders is null, .Any() throws. LINQ extension methods operate on the source collection directly and have no built-in null guards.
Step-by-Step Fix
1. Guard against null source collections
WRONG — calling LINQ on a null sequence:
List<Customer> customers = GetCustomers(); // might return null
var active = customers.Where(c => c.IsActive); // NullReferenceException
RIGHT — use null-coalescing or a guard:
List<Customer> customers = GetCustomers() ?? new List<Customer>();
var active = customers.Where(c => c.IsActive);
Or use the null-conditional operator (C# 6+):
var active = customers?.Where(c => c.IsActive) ?? Enumerable.Empty<Customer>();
2. Handle null elements in the sequence
WRONG — accessing properties on null elements:
var names = customers.Select(c => c.Name.ToUpper()); // NullReferenceException if any c is null
RIGHT — filter nulls first:
var names = customers
.Where(c => c != null)
.Select(c => c.Name.ToUpper());
Or handle within the expression:
var names = customers.Select(c => c?.Name?.ToUpper() ?? "UNKNOWN");
3. Guard against null child collections
WRONG — calling Any() on a null child collection:
var bigSpenders = customers.Where(c => c.Orders.Any(o => o.Amount > 1000));
RIGHT — use null-conditional or default:
var bigSpenders = customers.Where(c =>
c.Orders != null && c.Orders.Any(o => o.Amount > 1000));
Or with null-conditional:
var bigSpenders = customers.Where(c =>
c.Orders?.Any(o => o.Amount > 1000) == true);
4. Handle First() vs FirstOrDefault()
WRONG — First() throws when no match:
var vip = customers.Where(c => c.IsVip).First(); // InvalidOperationException
RIGHT — use FirstOrDefault() and check for null:
var vip = customers.Where(c => c.IsVip).FirstOrDefault();
if (vip != null)
{
Console.WriteLine(vip.Name);
}
Expected output: prints the VIP name or nothing if no VIP exists.
5. Null-safe grouping
WRONG — grouping by a nullable key:
var groups = customers.GroupBy(c => c.Category);
// If any c.Category is null, that group has key "" (empty)
RIGHT — handle null keys explicitly:
var groups = customers.GroupBy(c => c.Category ?? "Uncategorized");
Prevention
- Use
?.and??operators when chaining LINQ expressions. - Return empty collections instead of null from methods (use
Enumerable.Empty<T>()). - Filter null elements with
.Where(x => x != null)early in the chain. - Prefer
FirstOrDefault()overFirst()andSingleOrDefault()overSingle(). - Use nullable reference types (C# 8+) to catch null issues at compile time.
Common Mistakes with linq error
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro