Skip to content

C# LINQ NullReferenceException Fix

DodaTech Updated 2026-06-24 3 min read

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() over First() and SingleOrDefault() over Single().
  • Use nullable reference types (C# 8+) to catch null issues at compile time.

Common Mistakes with linq error

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. 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

### Why does LINQ throw NullReferenceException and not a LINQ-specific error?

LINQ methods are extension methods on IEnumerable. They don't add their own null checks — they call methods on the iterator directly. A null source passes through the method and causes a NullReferenceException when the method tries to call GetEnumerator() internally.

Does FirstOrDefault() protect against null collections?

No. FirstOrDefault() only protects against empty sequences by returning default(T) instead of throwing. If the source collection itself is null, FirstOrDefault() throws NullReferenceException just like any other LINQ method.

How do nullable reference types help with LINQ?

With nullable reference types enabled, you get compiler warnings when:

  • A variable might be null when passed to LINQ
  • A Select expression accesses a member on a potentially null element
  • A method parameter is nullable but LINQ expects non-null

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro