Fix "Object reference not set to an instance of an object" (NullReferenceException) in C#
System.NullReferenceException: Object reference not set to an instance of an object. at MyApp.Program.Main(String[] args) in C:\src\MyApp\Program.cs:line 12
- NullReferenceException: Object reference not set to an instance of an object PlayerController.Update () (at Assets/Scripts/PlayerController.cs:15)
- System.NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet.
- An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object.
- warning CS8602: Dereference of a possibly null reference.
- warning CS8618: Non-nullable property 'Name' must contain a non-null value when exiting constructor.
You use a member (method, property, indexer) of a variable that is null. Find the line shown in the stack trace, identify which reference is null with the debugger, then initialise it or handle the case with ?., ?? or an is null check; enable nullable reference types so the compiler warns you.
What this error means
In C#, a reference-type variable (class, string, array, interface) holds either the address of an object or null. Accessing a member through a null reference is impossible: the .NET runtime throws System.NullReferenceException with this generic message, without saying which expression was null. The only reliable information is the file and line number in the stack trace (present when the .pdb files are deployed). On a line like order.Customer.Address.City, any of the three accesses can be the culprit: the debugger or intermediate variables let you tell which.
Common causes
- Object never instantiated: a field or property declared but never assigned, a list declared without
new(). - Method that returns
null:FirstOrDefault(),Find(),GetComponent<T>()in Unity,Session[...]or JSON deserialisation with a missing field. - Unity: reference not assigned in the Inspector: a
publicor[SerializeField]field left as "None", or a destroyed object. - ASP.NET Core: Razor view called without a model (
return View();), Entity Framework navigation not loaded (noInclude), missing configuration.
Step-by-step fix
-
Find the line and the null expression
Open the
in ...cs:line 12line from the stack trace. In Visual Studio or Rider, run with the debugger: execution stops on the exception and the tooltip or the "Locals" window shows which variable isnull. -
Initialise what must always exist
If the object must exist, create it at declaration or in the constructor. Empty collections avoid most NREs.
public class Cart { public List<Item> Items { get; } = new(); public string Name { get; set; } = string.Empty; } -
Handle
nullwhen it is expected?.returnsnullinstead of crashing,??provides a default value,??=initialises when needed. For a lookup, test the result before using it.string city = order.Customer?.Address?.City ?? "Unknown"; _cache ??= new Dictionary<string, User>(); var user = users.FirstOrDefault(u => u.Email == email); if (user is null) { return NotFound(); } -
Fail early on mandatory parameters
Instead of an NRE far from the cause, validate arguments when entering the method (.NET 6+). The exception then names the parameter.
public void Ship(Order order) { ArgumentNullException.ThrowIfNull(order); // ... } -
Enable nullable reference types
With
<Nullable>enable</Nullable>(on by default in new .NET projects), the compiler flags risky dereferences (CS8602) and uninitialised properties (CS8618). Treating them as errors keeps the NRE out of production.<PropertyGroup> <Nullable>enable</Nullable> <WarningsAsErrors>nullable</WarningsAsErrors> </PropertyGroup> -
Unity case
Assign the field in the Inspector or fetch the component in
Awake(). For Unity objects, test with== nullorTryGetComponent:?.and??do not detect a destroyed object, because Unity overrides the==operator.[SerializeField] private Rigidbody rb; void Awake() { if (rb == null && !TryGetComponent(out rb)) { Debug.LogError("Rigidbody missing on " + name, this); } }
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Keep nullable reference types enabled and do not silence warnings with the
!operator unless you have checked the value cannot be null. - Initialise collections and strings at declaration, and prefer constructors that require the essential dependencies.
- Deploy the
.pdbfiles (or use embedded symbols) so production stack traces show line numbers.
Frequently asked questions
Why does the message not say which variable is null?
The .NET runtime does not keep that information when the error happens. Use the line number, the debugger, or split a long call chain into intermediate variables to isolate the culprit.
Should I catch NullReferenceException with try/catch?
No: it is always a bug in the code. Fix the cause or test for null explicitly; a catch would hide the problem and leave inconsistent state.
Why does GetComponent return null in Unity?
The component is not on the same GameObject (it is on a child or parent), or the script runs before the object is ready. Use GetComponentInChildren, assign the reference in the Inspector, or check the Awake / Start order.
Useful tools for this error
More Java, Kotlin & .NET errors
- Fix "java.lang.NullPointerException: Cannot invoke … because … is null" in Java
- Fix "UnsupportedClassVersionError: compiled by a more recent version of the Java Runtime"
- Fix "Could not resolve all files for configuration" and "Could not find" in Gradle
- Fix "Web server failed to start. Port 8080 was already in use" in Spring Boot
- Fix "Failed to configure a DataSource: 'url' attribute is not specified" in Spring Boot
- Fix "java.lang.OutOfMemoryError: Java heap space" (and GC overhead limit exceeded)
- Fix "lateinit property binding has not been initialized" in Kotlin (Android)