Improving Rider and ReSharper code analysis using JetBrains Annotations

One of the common questions we often get when meeting our users is this: “Can you show me something I did not know about Rider or ReSharper?” A great example would probably be the use of JetBrains Annotations – an easy way to improve Rider (and ReSharper’s) code analysis and functionality. In the next three blog posts, let’s see what they are and how we can use them to help other developers working with our code!

In this series:

What better way to start this series than to provide just an example, without the nitty-gritty details? Here goes!

A quick example…

Let’s say we are extending ASP.NET MVC’s HtmlHelper with a utility method of our own. The extension method takes three parameters: the HtmlHelper we are extending, a controller name and an action. Here’s the signature:

public static MvcHtmlString LoginLink(this HtmlHelper current,
    string controller, string action);

In our Razor view, it is all too easy to make a mistake when calling this helper method.

@Html.LoginLink("Index", "Home")

Did you spot the issue? We have accidentally mixed up the controller and action parameter. This will not be an issue at compile time, but things would break at run time. Given these are just strings that ASP.NET MVC passes around, making this kind of mistakes is bound to happen. Unless there would be a way to help our tools help us…

Cue JetBrains Annotations! Let’s skip how to add them into our project for a minute, and annotate our helper method’s arguments with [AspMvcController] and [AspMvcAction]:

public static MvcHtmlString LoginLink(this HtmlHelper current,
    [AspMvcController]string controller, [AspMvcAction]string action)

Doing this makes Rider (and ReSharper) effectively smarter. When using our utility method, the editor will show an error – telling us there is no IndexController with a Home action. Even better: we told our IDE that we expect the name of a controller, so we’ll also get code completion for our method!

Annotating our own HtmlHelper extension to provide code completion

Adding two attributes in our code, we helped ourselves and our colleagues by helping to prevent errors, adding code completion and navigation (go ahead, Ctrl+Click the controller or action name). We could even help consumers of our libraries by shipping annotations support!

A full overview of all available annotations is available in our web help. In our next post we’ll look at some background around what these annotations are, and how we can start using them in our code. Stay tuned for more!

Download the latest Rider or give ReSharper a try! We’d love to hear your feedback!

image description