We warned you, and it happened. About a year ago, my colleagues wrote an article in which they warned that the introduction of Nullable Reference types will not protect against dereferencing null references. Now we have indisputable proof of what we were saying found in the depths of Roslyn.

Nullable Reference Types

The idea itself of adding_ Nullable Reference_ (further as NR) types seems noteworthy to me since the problem related to dereferencing null references is still relevant to this day. Nevertheless, the implementation of protection against dereferencing turned out to be extremely unreliable. According to the idea of creators, only those variables whose type is marked with the “?” symbol can accept the null value. For example, a variable of the string? type indicates that it might contain null, and a variable of the string type might imply the opposite

However, nobody’s stopping us from passing null to non-nullable reference variables (further as - NNR) of types, because they are not implemented at the IL code level. The compiler’s built-in static analyzer is responsible for this limitation. Therefore, this new feature is more of a recommendation. Here is a simple example showing how it works:

C#

1

#nullable enable

2

object? nullable = null;

3

object nonNullable = nullable;

4

var deref = nonNullable.ToString();

As we can see, the nonNullable type is specified as NNR, but we can safely pass null there. Of course, we will get a warning about converting “Converting null literal or possible null value to non-nullable type”. However, we can get around it a bit more aggressively:

C#

1

#nullable enable

2

object? nullable = null;

3

object nonNullable = nullable!; // <=

4

var deref = nonNullable.ToString();

One exclamation mark and there are no warnings. If you’re a nitpicker, the following option is also available:

C#

1

#nullable enable

2

object nonNullable = null!;

3

var deref = nonNullable.ToString();

Here’s another example. Let’s create two simple console projects. In the first we write:

C#

1

namespace NullableTests

2

{

3

    public static class Tester

4

    {

5

        public static string RetNull() => null;

6

    }

7

}

In the second one we write:

C#

1

#nullable enable 

2

3

namespace ConsoleApp1

4

{

5

    class Program

6

    {

7

        static void Main(string[] args)

8

        {

9

            string? nullOrNotNull = NullableTests.Tester.RetNull();

10

            System.Console.WriteLine(nullOrNotNull.Length);

11

        }

12

    }

13

}

Hover the cursor over nullOrNotNull and see this message:

string

#dotnet #web dev #visual studio #csharp #bugs #pvs-studio #static code analysis #roslyn #procedural programming #static code analyzer

Nullable Reference Will Not Protect you, and Here Is the Proof
1.25 GEEK