Skip to content

Fix: C# System.NullReferenceException: Object reference not set to an instance of an object

FixDevs ·

Quick Answer

How to fix C# NullReferenceException caused by uninitialized objects, null returns, LINQ results, async/await, dependency injection, and Entity Framework navigation properties.

The Error

You run a C# application and get:

System.NullReferenceException: Object reference not set to an instance of an object.
   at MyApp.Program.Main(String[] args) in Program.cs:line 15

Or in ASP.NET:

NullReferenceException: Object reference not set to an instance of an object.
   at MyApp.Controllers.UserController.GetProfile() in UserController.cs:line 42

You tried to access a member (property, method, or field) on an object that is null. Since null does not have properties or methods, C# throws NullReferenceException.

Why This Happens

In C#, reference types default to null if not explicitly initialized. When you call a method or access a property on a null reference, the runtime throws this exception.

string name = null;
int length = name.Length;  // NullReferenceException

Common causes:

  • Uninitialized variable. Declared an object but never assigned it.
  • Method returned null. A method returned null instead of an expected object.
  • LINQ returned null. FirstOrDefault(), SingleOrDefault(), or dictionary access returned null.
  • Dependency injection failure. A service was not registered in the DI container.
  • Entity Framework navigation property not loaded. Related entities were not included in the query.
  • Async method returned null. An async method returned null instead of a Task.
  • Event handler not attached. Invoking an event with no subscribers.

Fix 1: Use Null Checks

The most basic fix. Check for null before accessing members:

string name = GetUserName();

if (name != null)
{
    Console.WriteLine(name.Length);
}

Pattern matching (C# 7+):

if (name is not null)
{
    Console.WriteLine(name.Length);
}

Guard clause for method parameters:

public void ProcessUser(User user)
{
    if (user == null)
        throw new ArgumentNullException(nameof(user));

    // Safe to use user here
    Console.WriteLine(user.Name);
}

C# 10+ simplified:

public void ProcessUser(User user)
{
    ArgumentNullException.ThrowIfNull(user);
    Console.WriteLine(user.Name);
}

Fix 2: Use the Null-Conditional Operator (?.)

The ?. operator short-circuits to null if the left side is null:

// Instead of:
string city = null;
if (user != null && user.Address != null)
{
    city = user.Address.City;
}

// Use:
string? city = user?.Address?.City;

If user is null, the entire expression returns null without throwing. If user.Address is null, same thing.

With method calls:

int? length = name?.Length;
string? upper = name?.ToUpper();

With indexers:

string? first = list?[0];
string? value = dict?["key"];

With events:

// Old way:
if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(name));

// New way:
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

Pro Tip: Use ?. liberally for chains of property access where any part might be null. But do not use it to silently swallow errors. If a value should never be null, it is better to let the NullReferenceException surface so you can fix the root cause.

Fix 3: Use the Null-Coalescing Operator (??)

Provide a default value when something might be null:

string name = GetUserName() ?? "Unknown";
int count = GetItems()?.Count ?? 0;
string city = user?.Address?.City ?? "Not specified";

With throw expressions:

string name = GetUserName()
    ?? throw new InvalidOperationException("User name is required");

Null-coalescing assignment (??=):

// Initialize only if null:
_cache ??= new Dictionary<string, object>();

Fix 4: Enable Nullable Reference Types

C# 8+ has nullable reference types that catch null issues at compile time:

In your .csproj:

<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

Now the compiler warns when you use a nullable type without checking:

string? name = GetName();    // Nullable — might be null
string title = GetTitle();   // Non-nullable — should never be null

Console.WriteLine(name.Length);  // Warning CS8602: Dereference of a possibly null reference
Console.WriteLine(title.Length); // No warning — title is non-nullable

This catches most NullReferenceException issues before you even run the code.

Fix the warnings:

if (name is not null)
{
    Console.WriteLine(name.Length);  // No warning after null check
}

Fix 5: Fix LINQ Null Results

FirstOrDefault(), SingleOrDefault(), and dictionary lookups return null (or default) when no match is found:

Broken:

var user = users.FirstOrDefault(u => u.Id == userId);
Console.WriteLine(user.Name);  // NullReferenceException if no match!

Fixed:

var user = users.FirstOrDefault(u => u.Id == userId);
if (user != null)
{
    Console.WriteLine(user.Name);
}

Or use First() with a clear exception:

var user = users.First(u => u.Id == userId);
// Throws InvalidOperationException with a clear message if not found

Dictionary access:

// Throws KeyNotFoundException:
var value = dict["missingKey"];

// Returns false if missing:
if (dict.TryGetValue("key", out var value))
{
    Console.WriteLine(value);
}

For similar key access issues in Python, see Fix: Python KeyError.

Fix 6: Fix Dependency Injection Issues

In ASP.NET Core, NullReferenceException on an injected service usually means it was not registered:

Broken:

public class UserController : ControllerBase
{
    private readonly IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    public IActionResult GetProfile()
    {
        var user = _userService.GetCurrentUser();  // NullReferenceException if _userService is null
    }
}

Fix: Register the service in Program.cs:

builder.Services.AddScoped<IUserService, UserService>();

If the service is registered but still null, check:

  • The interface and implementation match
  • The service lifetime is correct (Scoped, Transient, Singleton)
  • You are not manually constructing the controller with new

Fix 7: Fix Entity Framework Navigation Properties

EF Core navigation properties are null unless explicitly loaded:

Broken:

var order = context.Orders.First(o => o.Id == orderId);
Console.WriteLine(order.Customer.Name);  // NullReferenceException!

Fixed — eager loading with Include:

var order = context.Orders
    .Include(o => o.Customer)
    .First(o => o.Id == orderId);
Console.WriteLine(order.Customer.Name);  // Works

Fixed — explicit loading:

var order = context.Orders.First(o => o.Id == orderId);
context.Entry(order).Reference(o => o.Customer).Load();
Console.WriteLine(order.Customer.Name);

For similar database-related issues, see Fix: PostgreSQL relation does not exist.

Common Mistake: Assuming navigation properties are automatically loaded. EF Core uses lazy loading only if you explicitly configure it (with proxies or ILazyLoader). By default, navigation properties are null unless you use .Include(), explicit loading, or projection (.Select()).

Fix 8: Fix Async/Await Null Issues

Broken — returning null from an async method:

public async Task<User> GetUserAsync(int id)
{
    var user = await _repository.FindAsync(id);
    return user;  // Can return null
}

// Caller:
var user = await GetUserAsync(123);
Console.WriteLine(user.Name);  // NullReferenceException if user is null

Fixed:

var user = await GetUserAsync(123);
if (user is null)
{
    return NotFound();
}
Console.WriteLine(user.Name);

Broken — forgetting to await:

var task = GetUserAsync(123);  // This is a Task<User>, not a User!
Console.WriteLine(task.Name);  // NullReferenceException or compile error

Fixed:

var user = await GetUserAsync(123);
Console.WriteLine(user.Name);

Fix 9: Debug NullReferenceException

Read the stack trace. The line number tells you exactly where the null access happened. Look at that line and identify which object is null.

Multiple accesses on one line:

// Line 15:
var city = order.Customer.Address.City;

If line 15 throws, any of order, Customer, or Address could be null. Split the line to identify:

var customer = order.Customer;    // Check if this is null
var address = customer.Address;   // Check if this is null
var city = address.City;          // Check if this is null

Use the debugger. Set a breakpoint on the throwing line. Inspect each variable in the watch window.

Add null checks temporarily for debugging:

Console.WriteLine($"order: {order != null}");
Console.WriteLine($"customer: {order?.Customer != null}");
Console.WriteLine($"address: {order?.Customer?.Address != null}");

Still Not Working?

If you have checked all the fixes above:

Check for race conditions. In multi-threaded code, an object might be set to null between your null check and your access. Use Interlocked or locks for thread safety.

Check for disposed objects. Accessing properties on a disposed DbContext, HttpClient, or Stream can throw NullReferenceException or ObjectDisposedException. Make sure the object’s lifetime encompasses your usage.

Check for Unity-specific null. In Unity, destroyed GameObjects and Components have a custom null check. gameObject != null can return false even when the C# reference is not technically null. Use the Unity null check operator, not C# pattern matching.

Check deserialized objects. JSON or XML deserialization can produce objects with null properties if the source data is missing fields. Validate after deserialization.

Check for value types boxed as null. A Nullable<int> (int?) can be null, and unboxing it throws NullReferenceException:

object boxed = null;
int value = (int)boxed;  // NullReferenceException

For the related JavaScript version of this error, see Fix: TypeError: Cannot read properties of undefined.

F

FixDevs

Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.

Was this article helpful?

Related Articles