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
- Get yourself Visual Studio 2019
- Set C#8 as your project language
Project properties > Build > Advanced > Language version = C# 8.0
- Treat specific warnings as errors
Project properties > Build > Treat warning as errors > Specific errors: CS8600,CS8602,CS8603
#nullable enablecompiler declaration before any code in your
You can also can do it by editing your
<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.