liveBook · Manning

Null-forgiving operator

As explained in .NET in Action, Second Edition

The null-forgiving operator is the C# postfix ! operator that suppresses compiler nullability warnings without changing runtime behavior.

The null-forgiving operator is the postfix ! in C#. Writing a value such as null! suppresses a compiler nullability warning by asserting that the value will be assigned later. It changes no runtime behavior: it is effectively “null for now, but don’t worry about it.” section 8.2

EF Core DbSet initialization

EF Core populates DbSet properties, but the compiler cannot recognize that initialization path. Declare the property as `public DbSet<Comic> Comics { get; set; } = null!;` to silence the warning while leaving runtime assignment to EF Core. section 8.2

Listing 8.3 ComicDbContext class with no specified database
using Microsoft.EntityFrameworkCore;
  
namespace XkcdComicFinder;
  
public class ComicDbContext : DbContext
{
  public DbSet<Comic> Comics { get; set; } = null!;    #1
 
  public ComicDbContext(DbContextOptions options) :    #2
    base(options) { }
}

Inspect the complete ComicDbContext declaration, including the null-forgiving DbSet property and injected DbContextOptions. section 8.2

How .NET in Action, Second Edition covers it

How deep it goes
Defines the postfix syntax and compiler effect, but stops short of broader nullable-reference-type rules.
Examples
Uses a ComicDbContext whose Comics DbSet is declared with `= null!;`.
What it assumes
Assumes familiarity with C# properties and compiler warnings while explaining the operator’s syntax from context.
What you can do after
Apply it to defer compiler nullability checks for framework-populated properties without implying runtime validation.
How it connects
Connects nullable reference types with Entity Framework Core, DbContext, and DbSet initialization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.