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.
string? name = null; Console.WriteLine(name.Length); // warning CS8602, throws NullReferenceException Console.WriteLine(name?.Length); // prints an empty line
Try 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.
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
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
TryGetValueout values,FirstOrDefault,ascasts), 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!.Lengthstill throws whenxis null. - Value types cannot be null, except
Nullable<T>: reading.Valueon an emptyint?throwsInvalidOperationException, not this exception. - Strings: use
string.IsNullOrEmptyandstring.IsNullOrWhiteSpacefor input checks. - Prefer empty collections to null. Return
[]orArray.Empty<T>()so callers can loop safely. ?.chains short-circuit the whole chain:a?.b.cskips both.band.cifais null (but.cstill throws ifbis null).- Null object pattern. An object that does nothing can replace null in some designs.