What does NullReferenceException mean in C#?
Where null values come from
A variable that holds a reference type can be null until something assigns it. Calling a method, reading a property, or indexing into it while it is null throws this exception. The stack trace points to the line that used the reference, but the real cause is often earlier, where the value was never set.
Common causes include a lookup that returned nothing, a constructor that skipped setup, or a configuration value that was not loaded. A null check at the point of use prevents the crash but may hide the root issue, so check why the value is missing too.
- Check the line in the stack trace
- Trace the variable back to where it was set
- Add null checks where missing values are expected
- Use nullable annotations to flag risky spots
Preventing the crash
Validate inputs early so bad data does not reach deep code. Return clear values or throw a descriptive error when something required is missing. A clear message helps the next developer, including you, find the problem faster.
Log the variable and its context when a null value shows up unexpectedly. A short message with the caller name and input values gives you a trail to follow, which is far faster than guessing.
Common mistakes
- Adding a null check everywhere without fixing the source of the missing value.
- Ignoring the stack trace line and searching only for the exception name.

Related questions
- What does NullPointerException mean in Java?
- How do I fix IndexError: list index out of range in Python?
- What does TypeError: 'NoneType' object is not subscriptable mean?
- Why do I get a segmentation fault in C?
- What does ValueError: could not convert string to float mean?
- How do I fix a stack overflow error?