Skip to content
  1. LuzineDebug
  2. Java, Kotlin & .NET
  3. System.NullReferenceException: Object reference…
Java, Kotlin & .NET Beginner ≈ 10 min to fix

Fix "Object reference not set to an instance of an object" (NullReferenceException) in C#

Error message
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.
In short

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.

Be the first to confirm this fix

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

  1. Object never instantiated: a field or property declared but never assigned, a list declared without new().
  2. Method that returns null: FirstOrDefault(), Find(), GetComponent<T>() in Unity, Session[...] or JSON deserialisation with a missing field.
  3. Unity: reference not assigned in the Inspector: a public or [SerializeField] field left as "None", or a destroyed object.
  4. ASP.NET Core: Razor view called without a model (return View();), Entity Framework navigation not loaded (no Include), missing configuration.

Step-by-step fix

  1. Find the line and the null expression

    Open the in ...cs:line 12 line 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 is null.

  2. Initialise what must always exist

    If the object must exist, create it at declaration or in the constructor. Empty collections avoid most NREs.

    csharp
    public class Cart
    {
        public List<Item> Items { get; } = new();
        public string Name { get; set; } = string.Empty;
    }
  3. Handle null when it is expected

    ?. returns null instead of crashing, ?? provides a default value, ??= initialises when needed. For a lookup, test the result before using it.

    csharp
    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();
    }
  4. 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.

    csharp
    public void Ship(Order order)
    {
        ArgumentNullException.ThrowIfNull(order);
        // ...
    }
  5. 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.

    xml
    <PropertyGroup>
      <Nullable>enable</Nullable>
      <WarningsAsErrors>nullable</WarningsAsErrors>
    </PropertyGroup>
  6. Unity case

    Assign the field in the Inspector or fetch the component in Awake(). For Unity objects, test with == null or TryGetComponent: ?. and ?? do not detect a destroyed object, because Unity overrides the == operator.

    csharp
    [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 .pdb files (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

All Java, Kotlin & .NET errors →