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:
var xe = XElement.Parse("<test/>"); var attrib = xe.Attribute("a"); var value = attrib.Value;
Value this way is not very safe, ReSharper underlines it and, moving the mouse over the location shows the following pop-up.
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 context action to automatically fetch the package.
- You can simply add a project reference to the JetBrains.Annotations.dll, which you can find in the ReSharper installation directory..
- You can also insert attribute declarations anywhere in your project. If necessary, you can insert them into other namespace.
You can copy the declarations on the page of ReSharper options. Optionally, you can choose to make the declarations internal and/or add the
[Conditional("JETBRAINS_ANNOTATIONS")]attribute to the declarations.
Now, you can decorate your own method parameters with these attributes, and ReSharper will pick up on them: