System.NullReferenceException: Object reference not set to an instance of an object.
Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.
Root Cause
Often dubbed 'The Billion Dollar Mistake', the NullReferenceException in C# (and similar errors in other languages) occurs when you try to access a member (method, property, or field) of a reference type variable that currently holds the value `null`. `null` means the variable doesn't point to any object in memory. This frequently happens when an API call fails and returns null, when a database query yields no results, or when an object is declared but never instantiated with the `new` keyword. Failing to check for null before using the variable will cause the runtime to throw this exception, immediately crashing the current execution path.
Fix / Solution
Always initialize variables. Use defensive programming to check if an object is null before accessing its members. In modern C# (8.0+), enable Nullable Reference Types (`<Nullable>enable</Nullable>` in the .csproj) to get compiler warnings about potential null dereferences. Utilize the null-conditional operator (`?.`) and the null-coalescing operator (`??`) to handle nulls gracefully without verbose `if` statements.
Code Snippet
// ❌ Broken (Throws exception if user is null)
User user = GetUserFromDatabase(id);
string name = user.Name;
// ✅ Fixed (Traditional null check)
User user = GetUserFromDatabase(id);
if (user != null) {
string name = user.Name;
}
// ✅ Fixed (Modern C# — Null-conditional operator)
User? user = GetUserFromDatabase(id);
string? name = user?.Name; // name is null if user is null
string displayName = user?.Name ?? "Unknown User"; // Fallback value