Enable warnings about possible null references in your Visual Studio project

All .NET programmers had dealt at least once on their career with a null reference exception on a code line they wrote. Most of the times a parameter of a method is null, the code is not aware of it and the parameter is being used inside the method, for example we are accessing a property of an object. Because the value of the object is null we are getting an exception on the runtime.

Visual Studio provides a way to inform / warn us about possible null references. Let us see how we can enable this feature on our C# project.

We first define a test method on a new created .NET Web App Project in Visual Studio:

1
2
3
4
5
6
7
8
    public string TestMethod(string? testString, WeatherForecast? weatherForecast)
    {
        weatherForecast.Date = DateOnly.MinValue;

        string testString2 = testString.Trim();

        return testString2;
    }

as you can see both parameters are defined as nullable (the ? symbol), this means that we explicitly define that they can also carry the null value. This is the Nullable Annotations feature introduced in C# 8.

We then go to our .csproj file of our project and we are adding the <Nullable>enable</Nullable> attribute in the upper PropertyGroup area.

The Nullable attribute can take the three following values:

Now Visual Studio shows us warnings for possible null references in the Error List tab on the bottom of the window:

Possible null reference exception warning in Visual Studio

This feature let us build some more defensive code with null checks or assigning default values to properties which contain the null value. Speaking of default values assignment, let us check a cool syntax C# provides us.

Bonus: A cool trick to assign a default value to a null property

When a property has a null value, we can assign to it a default value by using the following syntax

1
2
3
4
5
6
7
8
9
10
11
    public string TestMethod(string? testString)
    {
        if (testString == null) {
            testString = "test";
        }

        return testString.Trim();
    }

    // Or we could write the following syntax:
    string testString2 = testString ?? "test";

However, we can greatly simplify the previous example into one line with the help of the ??= syntax:

1
2
3
4
5
6
    public string TestMethod(string? testString)
    {
        string testString2 ??= "test";

        return testString2.Trim();
    }
comments powered by Disqus