CKTIS / C#
NullReferenceException — using a null reference
System.NullReferenceException signals an attempt to dereference null, such as reading a property on an object that does not exist. Learn the cause, the role of nullable analysis, and the difference between !, ?., and ??.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
try { /* dereference */ } catch (System.NullReferenceException ex) { /* diagnostic handling */ }System.NullReferenceException is thrown when code attempts to dereference null, for example by reading text.Length when text is null. Inspect the location identified by the stack trace and intermediate values in a property-access chain.
With nullable analysis enabled, string? indicates that a reference may be null. Compiler warnings help identify risks but do not provide runtime protection. The ! operator only suppresses nullability warnings: text!.Length still throws if text is null.
Fix the cause: initialize the object or explicitly handle its absence. If a missing value is allowed, text?.Length ?? 0 returns 0 for null. Preventing this exception is usually preferable to catching it. The example uses catch only for demonstration; do not treat it as a normal way to check for null.
Examples
#nullable enable
using System;
internal static class Program
{
private static void Main()
{
string? text = null;
try
{
Console.WriteLine(text!.Length);
}
catch (System.NullReferenceException ex)
{
Console.WriteLine(ex.GetType().Name);
}
Console.WriteLine(text?.Length ?? 0);
}
}Result
NullReferenceException 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.