Migrate from Jetbrains.Annotations [NotNull] / [CanBeNull] to C# Nullable Reference Types

The most popular feature of JetBrains.Annotations is probably the addition of two cool attributes: [NotNull] and [CanBeNull]. They add a meta-information to a marked element, describing if null is a correct value for that element, or not. Then, developers using ReSharper would get help from the IDE and could easier avoid mistakes like here:

A screenshot demonstrating usage of the [CanBeNull] attribute in C#.
Using the [NotNull] attribute helps notice a mistake. Here, null is not a valid value to pass to the GetStringLength(string s) method, but developer attempted that and gets a warning.

I discovered them a few years ago when they were extensively used in a project I also worked on. At that time, there was no native support for anything similar in C#. I remember some of us always used it, and some of it avoided it and were against introducing some 3rd party library and attributes just to get some new warnings in the IDE. I have seen a high value in it. It became a standard part of my toolkit ever since.

Luckily, since C#8 we can mark types as non-nullable natively. We don’t need ReSharper or attributes from their library.

So, is there an easy, automated way, to migrate from Jetbrains.Annotations [NotNull]/[CanBeNull] usages to the modern Nullable Reference Types? Yes! But if you don’t want to replace each usage individually in the code editor, things needs to be done in the right order.

How to migrate solution using Visual Studio

I assume you start with a project that uses annotations, like here:

A screenshot demonstrating usage of the [NotNull] and [CanBeNull] attribute in C#.
Use the following steps to migrate to native nullable reference types:
  1. Don’t remove reference to the Jetbrains.Annotations package yet! It’s needed for the automated refactoring to work.
  2. Enable Nullable Reference types in the project by adding <Nullable>enable</Nullable> to your *.csproj file, or enable it in the Visual Studio’s UI.
  3. Use the refactoring named “Use type annotation syntax”, as depicted in a screenshot. You can choose the scope of a whole project or solution.
Migrating [NotNull] and [CanBeNull] to Nullable Reference Types in Visual Studio
  1. Now you can remove the reference to JetBrains.Annotations package. Check if the project still compiles. Your project might have usages of other, less popular attributes from the package that might or might not have a replacement in native C# or .NET features at this point – fix them individually.

I hope it helps you save some time 🙂

Leave a Comment