ReSharper – Our Favourite Features

| 7 min. (1319 words)

Just in case you don’t know what ReSharper is, it’s a plug-in for Visual Studio that adds awesome code navigation and editing features for Visual Studio. Our 5 favourite features are listed below. Anything you want to share? Comment below.

Resharper has a crazy amount of navigation shortcuts that can mean you never have to touch that pesky mouse again. We use the Visual Studio scheme for Resharper.

1. Navigation shortcuts

Ctrl + T in Resharper 9 navigates to anything by name. Classes, properties, methods, files, the lost city of Atlantis, you name it , it goes there.

If you are more inclined to use a mouse, Resharper adds a whole lot of things to the right click menu in the Text Editor. Right click on an interface name and pick Go to Implementation to jump to all implementations of that interface (go figure). Find All Usages is my personal favourite – this is bound to Ctrl-Shift-F12 by default, but it’s worth chucking it on something a little less spread out as it’s pretty handy.

2. Refactoring tools

Everyone has seen the Rename tool before, that’s something VS has supported for ages. Big deal I hear you say. Resharper adds a bunch more options though, ones you’ll definitely find useful.

Extract Variable and Extract Method are my favourites. If I’m staring at a big method with no idea what it does, I start ripping it apart with these two tools. Say we’ve got some code like this:

public void UpdateCustomerDetails(CustomerModel customer)
{
    var subscription = _subscriptionService.GetCustomer(Base64.DecodeID(customer.Id));

    if(ModelState.IsValid)
    {
        try
        {
            subscription.UpdateCustomerName(customer);
            subscription.UpdateCustomerBilling(customer);

            _unitOfWork.Update(customer);
            return RedirectToAction("Success");
        }
        catch(SubscriptionException e)
        {
            new RaygunClient().SendInBackground(e);
            _logger.LogException(e);

            if(exception.ErrorMessages.Any())
            {
                foreach(var em in exception.ErrorMessages)
                {
                    ModelState.AddModelError("", em.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", "An unknown error occurred");
            }
        }
    }

    return View();
}

First, extract a few properly named variables by selecting some code and hitting Ctrl + R, Ctrl + V. That Base64.DecodeID call looks like it should really be a variable called customerIdentifier to me, so I highlight Base64.DecodeID(customer.Id) and hit Ctrl + R, Ctrl + V, tell R# to call it customerIdentifier, and hit enter. At this point Resharper will also check the rest of the method to see if there are any other pieces of code that look like that, and offer to replace them as well.

There are a few other things that clutter this method up a bit. The error handling is noise and looks a bit generic – I’ll put that in a separate method for now and reuse it later if I can. If I select all the code inside the catch (from the new RaygunClient() call down to the last bracket of the else) then hit Ctrl + R, Ctrl + M Resharper will offer to create a method for me. I then tell it to call that method HandleSubscriptionException, and it creates the method below my current method.

After these two refactorings, we have the following code:

public void UpdateCustomerDetails(CustomerModel customer)
{
    var customerIdentifier = Base64.DecodeID(customer.Id);
    var subscription = _subscriptionService.GetCustomer(customerIdentifier);

    if(ModelState.IsValid)
    {
        try
        {
            subscription.UpdateCustomerName(customer);
            subscription.UpdateCustomerBilling(customer);

            _unitOfWork.Update(customer);
            return RedirectToAction("Success");
        }
        catch(SubscriptionException e)
        {
            HandleSubscriptionException(e);
        }
    }

    return View();
}

private void HandleSubscriptionException(SubscriptionException e)
{
    new RaygunClient().SendInBackground(e);
    _logger.LogException(e);

    if(exception.ErrorMessages.Any())
    {
        foreach(var em in exception.ErrorMessages)
        {
            ModelState.AddModelError("", em.Message);
        }
    }
    else
    {
        ModelState.AddModelError("", "An unknown error occurred");
    }
}

That looks a bit nicer now – we can see what’s going on now. If the new details are valid, we attempt to update the customer’s details in the subscription system. If there are any problems updating the subscription, we have an error handler that does something. All that with 2 keyboard shortcuts.

These are just two of the refactoring tools Resharper adds. It’s worth investigating Pull Methods Up which moves methods into their base class, Change Signature which lets you shuffle parameters around in method signatures, and Extract Class from Parameters which lets you wrap up a lot of method parameters into one DTO class.

3. Code Inspection

Resharper inspects your code as you are writing it, and can let you know if there are things wrong. These can be small things like inconsistent naming of variables or unused namespace using directives, or big things like MVC views not existing or THIS CODE DOESN’T EVEN COMPILE WHAT ARE YOU DOING? That last part is something I’ve always wanted Visual Studio to do out of the box, but it doesn’t so it’s helpful that Resharper can give me the red squiggly lines.

Resharper’s suggested fixes for the problems it finds are available by either pushing Alt + Enter on the indicator (it will be a squiggly line or grey code usually), or clicking the little icon it puts next to the line when you have your cursor inside the indicator. If it’s stuff like dead/useless code, it’ll give you the option to remove it.

If it’s something you think is unimportant, you can change the settings for that particular inspection to hide it – you find that in the same menu as the fixes. You can change the severity of the problem to Do not show, Hint, Suggestion, Warning, and Error, so if you think Unsed Namespaces are the worse thing ever then you can change that to an Error and have beautiful angry red squiggly lines screaming at you whenever it finds them.

4. Unit testing support

This one’s kinda minor – Visual studio has this built in but the Resharper version has a better UI in my opinion. Ctrl + U, L runs all the unit tests from the whole solution. Perfect for those final pre-commit checks to make sure you won’t be ridiculed by your workmates for breaking the build.

5. Code generation

Do you get bored of writing endless boilerplate when setting up a new project? Would you like to just code as if properties exist then let the computer do all the writing? I have just the thing for you! Alt + Insert pops open the Generate menu, which provides classics such as Generate Constructor, Generate Missing Members, and Do All My Work For Me. This doesn’t just work in the Text Editor, it works in the Solution Explorer too! Goodbye, hard to find Add menu!

Generate Constructor is really useful when writing new classes, as you can quickly add a bunch of properties to a new class (using the prop Code Template) then generate a new constructor that takes them all in.

Generate Equality Members is pretty handy if you need a class to implement GetHashCode(). It asks you for the properties which define equality for the class, then generates a decent GetHashCode() method as well as a set of Equals() methods that comply with the .NET guidelines on GetHashCode().

Not to be forgotten are Code Templates, which are short words that can be expanded into larger code constructs. You can see the available templates in the Resharper menu, Templates Explorer. Check them out, there’s a bunch of good ones like prop (new property), nguid (random new guid), and try (try catch block).

Conclusion

As you can see there are a ton of cool features in Resharper. Every time I give a talk about Resharper someone tells me about another one I didn’t know about – yesterday it was using Alt + Insert in the Solution Explorer. If I’ve missed your favourite tip, let me know in the comments.

On another note….

You might have just stumbled on this page and are wondering what Raygun Crash Reporting and Pulse do. Well, let us explain.

Crash Reporting keeps a watchful eye on your web and mobile applications and tells you when problems arise. Add Raygun to your code in minutes and you’ll be able to detect every error in your software, the second they happen.

Pulse is a Real User Monitoring tool for you web and mobile application. Ensure your team has the right information, with real time insight into performance and software usage.