Attempting to access a member or invoke a method on a variable that is null.
A NullReferenceException occurs at runtime when code attempts to dereference a object reference variable whose value is currently `null`.
Common causes: uninitialized class properties, database queries returning null when no record is found, or accessing properties on optional parameters without null checks.
1using System;2 3public class Program {4 public static void Main() {5 User user = null;6 Console.WriteLine(user.Name); // Throws NullReferenceException!7 }8}9 10public class User {11 public string Name { get; set; }12}1using System;2 3public class Program {4 public static void Main() {5 User user = GetUser() ?? new User { Name = "Guest" };6 7 // Fix 1: Null-conditional operator (?)8 Console.WriteLine(user?.Name);9 10 // Fix 2: Pattern matching guard11 if (user is { Name: var name }) {12 Console.WriteLine($"Hello, {name}");13 }14 }15 16 private static User GetUser() => null;17}18 19public class User {20 public string Name { get; set; }21}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Variable `user` is set to `null`. Attempting to read `user.Name` causes the CLR runtime to raise a System.NullReferenceException.