Value and Nullability Analysis
ReSharper performs value analysis to help you find possible 'null' dereferences as well as redundant boolean comparisons and nullability checks.
In this topic:
- Different ways of analyzing values
- Value and nullability analysis modes
- Further examples of value analysis
Different ways of analyzing values
ReSharper analyzes values in two general ways:
By understanding the behavior of language constructs.
In the example below, based on the fact that the parameter
objwas explicitly checked for nullability, ReSharper reasonably supposes that the value of
objcan be indeed 'null' and displays the corresponding warning:
By relying on
code annotation attributes
In this example, the method
Baris marked with the
[CanBeNull]attribute, Using this information, ReSharper warns you that the return value of
Barcan be null, and calling a method on it could lead to a 'null' dereference:
Value and nullability analysis modes
ReSharper can analyze values in different modes:
By default, value analysis mode is optimistic. In this mode, ReSharper only warns about possible 'null' dereference if the value was explicitly checked for nullability, or if the symbol is marked with the
[ItemCanBeNull]attribute. The optimistic mode is demonstrated in the examples above.
In this mode, ReSharper warns about possible 'null' dereference in all contexts where the value is not checked for nullability explicitly, unless the symbol is marked with the
Further examples of value analysis
Here are some more examples of ReSharper's value and nullability analysis:
- If a nullability check has been already done with a simple LINQ query, ReSharper tells you that a further nullability check is redundant:
The same happens if you mark a collection with the
- 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 ReSharper warns here about possible 'null' dereference.