C# 8 nullable reference types

C# 8 nullable reference types

In the previous article, we discussed C# 8 default interface methods. In this article, we’ll look at C# 8 nullable reference types. Reference types refer to an object that is on the heap. When there is no object to refer to, the value is null. Sometimes null is an acceptable value, but often it is an illegal value that leads to ArgumentNullExceptions and NullReferenceExceptions.

C# 8 finally gives us the ability to express whether a variable shouldn’t be null, and when it can be null. Based on these annotations, the compiler will warn you when you are potentially using a null reference, or passing a null reference to a function that won’t accept it.

To enable the feature, you must add the following line in the project file (csproj) PropertyGroup:

<Nullable>enable</Nullable>

Other values than enable are possible and make the compiler a bit more relaxed. It’s also possible to change this setting per file. See the nullable context documentation for more information.

The ? character is used to indicate when a type might be null. When the ? character is not present, the type is assumed to be non-nullable:

MyClass? mayBeNull = null;
MyClass  mayNotBeNull = new MyClass();

We can also use this syntax for method arguments and return values:

static MyClass Foo(MyClass? mayBeNull)
{
    return mayBeNull ?? new MyClass();
}

The method Foo accepts an argument that might be null, and returns an argument that is not.

The compiler doesn’t just rely on the type declaration. It also follows the code paths to understand when a type will no longer be null:

static void Bar(MyClass? arg)
{
    if (arg == null)
    {
        throw new ArgumentNullException(nameof(arg));
    }

    arg.Method();
}

In this example, the compiler understands that arg cannot be null when we call arg.Method since we’ve thrown for that earlier. If we leave out the null check, then we get a warning for the arg.Method call:

CS8602: Dereference of a possibly null reference.

Suppose that we had accidentally missed typing the throw keyword. In that case, we would also get that warning.

There might be cases where the compiler doesn’t understand that a variable can no longer be null. For example, if your class allows one method to only be called in a state where you are sure that a field has already been set. We can pass this information to the compiler using the null-forgiving operator (!):

string scheme = _uri!.Scheme; // _uri is of type Uri?
int port = _uri.Port;

Because we used the ! operator on the variable, the compiler knows it’s safe. We don’t need to use the null-forgiving operator on the next line when we access Port. The compiler infers that _uri can no longer be null.

The nullable annotations added to the method argument become part of the assembly as Attributes. .NET Core base libraries are being updated to include these annotations.

The compiler inspects within a method. When the method has strong guarantees regarding how it behaves for nullable arguments, the method can be augmented with Attributes that express this:

static void Bar(MyClass? arg)
{
    if (arg == null)
    {
        ThrowArgumentNull(nameof(arg));
    }

    arg.Method();
}

[DoesNotReturn]
public static void ThrowArgumentNull(string paramName)
{
    throw new ArgumentNullException(paramName);
}

In this simple example, we use the DoesNotReturn attribute, which tells the compiler that arg won’t be null past the if block because ThrowArgumentNull never returns. Some attributes can be conditional on values. For example, string.IsNullOrEmpty is annotated as follows:

public static bool IsNullOrEmpty([NotNullWhenAttribute(false)] string? value)

This annotation makes the compiler understand that the value argument isn’t null when this method returns false.

You can find these attributes and more in the System.Diagnostics.CodeAnalysis namespace. These attributes are available in .NET Core 3.x (and netstandard2.1).

Everything you need to grow your career.

With your free Red Hat Developer program membership, unlock our library of cheat sheets and ebooks on next-generation application development.

SIGN UP

Conclusion

C# 8 provides us with a mechanism to express when a reference type might be null and when it is not. Thanks to these annotations, we can now express the nullability expectations of APIs. The compiler uses this information to provide warnings that could otherwise cause unexpected exceptions at runtime.

C# 8 can be used with the .NET Core 3.1 SDK, which is available on RHEL, Fedora, Windows, macOS, and other Linux distributions.

Share