ASP.NET Core Best Practices

Chapter 1 · Practice 2 of 3

Turn on nullable reference types and treat warnings as errors

From Versions and project setup

Why it matters

NullReferenceException is the most common runtime error in C# code. With nullable reference types enabled, the compiler tracks which references can be null and warns when you dereference one without checking.

Warnings only help if someone reads them. Make them fail the build:

  • <Nullable>enable</Nullable> in every project (new templates do this already).
  • <TreatWarningsAsErrors>true</TreatWarningsAsErrors> so new warnings cannot be merged.
  • <AnalysisLevel>latest-recommended</AnalysisLevel> to turn on more of the built-in .NET analyzers.

Put shared settings in a Directory.Build.props at the repository root so every project gets them.

Example

XML
<Project>
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
  </PropertyGroup>
</Project>