Detect possible NullReferenceExceptions
A null check is one of the most common operations in .NET development. ReSharper is one tool that takes null checks seriously by providing special support to developers working with entities that can potentially be null.
The first thing ReSharper does is detect the possibility of a
NullReferenceException occurring. For example, say we try to access the value of an XML attribute without checking whether it exists first:
Value this way is not very safe, ReSharper underlines it and, moving the mouse over the location shows the following popup.
Placing the caret over the identifier and pressing Alt+Enter will show you a quick-fix that allows you to automatically do a null check on the variable:
Most of null checking done by ReSharper is implemented via code annotations, which work in two ways:
First of all, we have annotated a large amount of symbols from the .NET FCL as well as NUnit with attributes with External Annotations, which are included in the ReSharper installation. For instance, the
Attribute method in the above example is annotated this way with the
Here’s another example of externally annotated method: if we try to create a
Uri with a null parameter, we get the following popup message:
Of course, nothing prevents you from using these attributes in your own code. There are several way to add these attributes to your project:
The recommended way is to install the NuGet package with the
Actually, you do not even need to go to the NuGet website to get the package. Just add the
using JetBrains.Annotations;directive, and use the corresponding Alt+Enter action to automatically fetch the package.
You can also embed attribute declarations anywhere in your project, using the default
JetBrains.Annotationsnamespace, or any other namespace.
Now, you can decorate your own method parameters with these attributes, and ReSharper will pick up on them: