Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

NullReferenceException

Reference for NullReferenceException in C#: why it happens, how nullable reference types, ?., ?? and ArgumentNullException.ThrowIfNull prevent it.

NullReferenceException is thrown when you use a member of a reference that is null: calling a method, reading a property, indexing or reading a field. The reference points to no object, so there is nothing to run the member on.

It is one of the most common runtime errors in C#. Modern C# helps you avoid it: nullable reference types make the compiler warn about possible null dereferences, ?. and ?? handle null in an expression, and guard clauses reject null at the boundary.

C#
string? name = null;
Console.WriteLine(name.Length);   // warning CS8602, throws NullReferenceException
Console.WriteLine(name?.Length);  // prints an empty line

Try it

C# Causing and catching it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Guard clauses and null checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class NullReferenceException : SystemException
{
    public NullReferenceException();
    public NullReferenceException(string? message);
    public NullReferenceException(string? message, Exception? innerException);
}

The exception has no extra members. The runtime throws it; it is almost never right to throw it yourself (throw ArgumentNullException for a null argument).

Technique Effect
x?.Member Evaluates to null instead of throwing when x is null.
x ?? fallback Uses a fallback when x is null.
x is not null Explicit check before use.
ArgumentNullException.ThrowIfNull(x) Rejects null arguments early with a clear message.
string? annotation Declares that null is allowed, so the compiler checks uses.

Usage notes

  • Typical causes: uninitialized fields, a method that returns null (dictionary TryGetValue out values, FirstOrDefault, as casts), missing JSON properties, and objects not yet constructed.
  • Read the stack trace. The first frame shows where null was used. Work backwards to find where it came from.
  • Enable nullable reference types. <Nullable>enable</Nullable> is on in our runner. Treat warnings CS8600 to CS8604 as real bugs.
  • The ! operator only silences the compiler. x!.Length still throws when x is null.
  • Value types cannot be null, except Nullable<T>: reading .Value on an empty int? throws InvalidOperationException, not this exception.
  • Strings: use string.IsNullOrEmpty and string.IsNullOrWhiteSpace for input checks.
  • Prefer empty collections to null. Return [] or Array.Empty<T>() so callers can loop safely.
  • ?. chains short-circuit the whole chain: a?.b.c skips both .b and .c if a is null (but .c still throws if b is null).
  • Null object pattern. An object that does nothing can replace null in some designs.