Code inspection and many other JetBrains Rider features largely rely on knowing behavior of language constructs to detect issues, suggest possible improvements, and help you in other ways.
However, this kind of analysis cannot detect everything. For example, if a method is designed to never return null and its clients are designed accordingly, no structural analysis will find a possible issue if someone has changed the method to return null.
In this and a lot of other cases, the JetBrains Rider's JetBrains.Annotations is of a great help. By using attributes declared in this framework you can make JetBrains Rider analyze code the way you need it. For example:
[NotNull]publicobjectFoo(){returnnull;// Warning: Possible 'null' assignment}
This being the simplest example, there are other helpful attributes with more complex use cases. You can find the full list of these attributes in the reference.
In most cases, code annotation attributes enable specific code inspections, for example:
CanBeNullAttribute and NotNullAttribute are associated with the Possible 'null' assignment to entity marked with 'Value cannot be null' attribute. For more information, see Value and nullability analysis.
ContractAnnotationAttribute can be used to define contracts for your functions and turn on the corresponding inspections. For example, you can use [ContractAnnotation("input:null => false")] to notify the consumers of the function bool Foo(object input) that always returns false when parameter s is null.
JetBrains Rider allows you to annotate code symbols in two ways:
You can annotate symbols in your source code as shown in the example above. In this case, you need to reference JetBrains.Annotations namespace in your project. For more information, see Annotations in source code.
Even if you do not have access to sources, you can annotate symbols in compiled library code. For more information, see External annotations.
tip
Part of the work of annotating standard libraries (for example .NET Framework Class Library, NUnit Framework) with external annotations is already done and the external annotations for these libraries are included in the JetBrains Rider installation. So you can benefit from attributes driven inspections, quick-fixes, and other features when using these libraries.