JetBrains Rider 2024.1 Help

Code inspection: Possible 'null' assignment to non-nullable entity

The [NotNull] attribute introduces a contract to indicate that a particular symbol can never be null.

As the [NotNull] can be used nearly everywhere, there are different situations where this inspection can help you find violations of contracts that [NotNull] brings. Here are a couple of examples:

  • [NotNull] helps use your symbols marked accordingly without additional null checks.

    However, when you mark your public members with [NotNull], you have to make sure that they actually never return null. As soon as the annotation is there, JetBrains Rider will check if this contract is valid:

    [NotNull] public object CreateNotNullableObject() { return null; // Warning: Possible 'null' assignment to entity with '[NotNull]' attribute }
  • [NotNull] can also serve as a contract for parameters, for example if you check the parameter and throw ArgumentNullException if null is passed. In this case, JetBrains Rider will warn users of your method if they try to pass null value to the annotated parameter:

    public static void Foo([NotNull] string param) { if(param == null) throw new ArgumentNullException(nameof(param)); // Do something with 'param' } void Test() { Foo(null); // Warning: Possible 'null' assignment to entity with '[NotNull]' attribute }

Note that this inspection will is not limited to symbols marked with NotNull in your source code. This annotation can also be added via external annotations, and it is already there for related symbols in the .NET Framework Class Library and other frequently used libraries, as external annotations for these libraries are included in the JetBrains Rider installation.

Last modified: 11 February 2024