Rider Help

Value and Nullability Analysis

Rider performs value analysis to help you find possible 'null' dereferences as well as redundant boolean comparisons and nullability checks.

Different ways of analyzing values

Rider analyzes values in two general ways:

  • By understanding the behavior of language constructs.
    In the example below, based on the fact that the parameter obj was explicitly checked for nullability, Rider reasonably supposes that the value of obj can be indeed 'null' and displays the corresponding warning:
    /help/img/dotnet/2017.2/Code_Analysis__Value_Analysis__1.png
  • By relying on code annotation attributes ([CanBeNull], [NotNull], [ItemCanBeNull], [ItemNotNull])
    In this example, the method Bar is marked with the [CanBeNull] attribute, Using this information, Rider warns you that the return value of Bar can be null, and calling a method on it could lead to a 'null' dereference:
    /help/img/dotnet/2017.2/Code_Analysis__Value_Analysis__2.png

Value and nullability analysis modes

Rider can analyze values in different modes:

  • Optimistic
    By default, value analysis mode is optimistic. In this mode, Rider only warns about possible 'null' dereference if the value was explicitly checked for nullability, or if the symbol is marked with the [CanBeNull] or [ItemCanBeNull] attribute. The optimistic mode is demonstrated in the examples above.
  • Pessimistic
    In this mode, Rider warns about possible 'null' dereference in all contexts where the value is not checked for nullability explicitly, unless the symbol is marked with the [NotNull] or [ItemNotNull] attribute.

To change value analysis mode or disable the analysis, configure the Value analysis mode preference on the Code Inspection | Settings page of Rider options.

Further examples of value analysis

Here are some more examples of Rider's value and nullability analysis:

  • If a nullability check has been already done with a simple LINQ query, Rider tells you that a further nullability check is redundant:
    Redundant nullability check for collection item
  • The same happens if you mark a collection with the [ItemNotNull] attribute:
    Redundant nullability check for collection item
  • The next example illustrates how value analysis works when the pessimistic mode is enabled. The value of the list was checked for nullability, but not list items. Therefore Rider warns here about possible 'null' dereference.
    Redundant nullability check for collection item
Last modified: 11 October 2017

See Also