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 pop-up.
Placing the caret over the identifier and pressing Alt+Enter will show you a context action which allows you to do a
null check on the variable:
Another benefit of null checking is implemented in ReSharper via Custom Annotations. Essentially, we have annotated a large amount of symbols from the .NET FCL as well as NUnit with attributes that are subsequently used to help with development. Two of these attributes –
NotNullAttribute are useful in our case.
Here’s an example: 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. You can either use the
ReSharper.Annotations assembly or, if you’d rather not take another dependency, you can simply generate the annotations code (these are just empty attribute declarations) and paste it in your project under your own namespace. To do so, simply open up ReSharper | Options in the top menu, and navigate to Code Annotations in the tree. Now, press the button to copy the default implementation to the clipboard. Paste it in your code and you’re done.
Now, you can decorate your own method parameters with these attributes, and ReSharper will pick up on them: