ReSharper 2016.1 Help

Code Inspection: Possible 'null' assignment to entity with '[NotNull]' attribute

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 nullability 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, ReSharper 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, e.g. if you check the parameter and throw ArgumentNullException if null is passed. In this case, ReSharper 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 be also 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 ReSharper installation.

See Also

Last modified: 19 August 2016