Treat nulls as errors in C#8

Null Reference Types is a new feature that comes with C#8. Generally speaking, it's all about how nulls are treated. If you're new to this, you might watch Mads Torgersen, Bill Wagner talk at NDC London.

By default, unless you explicitly declare it, you'll get an warning when you assign null reference type to variable.

Yet, in most cases, you'd likely want to avoid nulls at all cost. By doing so, you deacrese possibility of null reference exception thrown in your application.

So it's not the bad idea to treat warnings about possible null occurence as errors.

Treat undeclared nulls as errors

  1. Get yourself Visual Studio 2019
  2. Set C#8 as your project language
    Project properties > Build > Advanced > Language version = C# 8.0
  3. Treat specific warnings as errors
    Project properties > Build > Treat warning as errors > Specific errors: CS8600,CS8602,CS8603
  1. Insert #nullable enable compiler declaration before any code in your .cs file

You can also can do it by editing your .csproj file

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    <WarningsAsErrors>CS8600,CS8602,CS8603</WarningsAsErrors>
  </PropertyGroup>

</Project>

From now on, whenever you assign null to any reference type variable, without declaring its nullability (adding ?), you will get an error telling about null assigment to non-nullable type.

Nulls marked by IDE as errors
Nulls treated as errors and not as just warnings
Treating CS8603 warning as error
comments powered by Disqus