liveBook · Manning

Nullable reference types

As explained in ASP.NET Core in Action, 3e

Nullable reference types are a C# compiler feature that represents and checks whether reference-type values may be null.

Nullable reference types (NRTs) are a C# compiler feature for stating whether reference-type values may be null. They help reduce null-reference exceptions by making optionality explicit and enabling compiler and IDE warnings. section 7.5 section 4.4

Use nullable annotations to make request-handling behavior match the values an endpoint can receive:

  • Mark an optional reference-type parameter with ?, such as Product?, when a missing or literal null request body should become a null handler argument. section 7.5
  • Keep NRTs enabled where possible; ASP.NET Core .NET 7 templates enable them by default, and disabling them can make types unexpectedly optional. section 7.5
  • Enable the feature in the project file with <Nullable>enable</Nullable>, or selectively with #nullable enable when whole-project activation is not practical. section 7.5 section 3.5
  • Use compiler analyzers and IDE hints to find mismatches between endpoint optionality and handler parameters before runtime. section 7.5
Listing 7.5 Using optional parameters in endpoint handlers
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.MapGet("/stock/{id?}", (int? id) => $"Received {id}");           #1
 
app.MapGet("/stock2", (int? id) => $"Received {id}");                #2
 
app.MapPost("/stock", (Product? product) => $"Received {product}");  #3
 
app.Run();

Shows nullable route, query-string, and body parameters in a small minimal API application. section 7.5

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains annotations, project enablement, binding behavior, and analyzer warnings, but does not descend into compiler implementation.
Examples
Demonstrates Product?, nullable route and query parameters, and a net7.0 project file with Nullable enabled.
What it assumes
Assumes basic C# project and endpoint familiarity while introducing NRTs as a C# 8 feature.
What you can do after
Apply nullable annotations and compiler or IDE warnings to configure safer optional parameters in minimal API endpoints.
How it connects
Connects nullable reference types with C# compiler analyzers, null-reference exceptions, model binding, and minimal APIs.

Also explained in

Compare how 2 books explain nullable reference types →

Related concepts

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