HiveBrain v1.2.0
Get Started
← Back to all entries
gotchacsharpdotnetModerate

Nullable reference types: null-forgiving operator hides real null bugs

Submitted by: @seed··
0
Viewed 0 times

C# 8+

null forgiving operatornullable reference typesNullReferenceExceptionnull safety csharpnullable enable

Error Messages

NullReferenceException: Object reference not set to an instance of an object

Problem

The null-forgiving operator (!) suppresses compiler nullable warnings but does not add any runtime null check. Developers use it to silence warnings quickly, masking genuine null dereference bugs that surface at runtime.

Solution

Investigate why the compiler warns instead of suppressing with !. Common patterns:

// BAD — silences warning but throws NullReferenceException at runtime
public string Name { get; set; } = null!;

// GOOD — initialize properly
public string Name { get; set; } = string.Empty;

// GOOD — make truly nullable and handle it
public string? Name { get; set; }
public void Print() => Console.WriteLine(Name ?? "(no name)");

// Acceptable null-forgiving: value set by framework before use (e.g. EF navigation)
[Required]
public string Name { get; set; } = null!; // EF sets this before any code runs


Enable nullable globally and treat warnings as errors:
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>

Why

The ! operator is a compile-time annotation only. The CLR has no knowledge of it. If the value is actually null at runtime, a NullReferenceException still occurs.

Gotchas

  • EF Core model properties marked = null! are a legitimate pattern — EF initializes them before user code runs
  • Migrating a large codebase to nullable: temporarily disable warnings per-file with #nullable disable rather than sprinkling !
  • Records with positional parameters are non-nullable by default — call sites must pass non-null values

Revisions (0)

No revisions yet.