ReSharper - The Magic Bullet For Visual Studio


Edited by Nina Miller

Introduction

When I was younger(much younger), I used to watch a cartoon called Underdog. Underdog was a fairly ordinary dog until he took a pill that turned him into a flying hero who saved the world from villains. That's the feeling I get when I use ReSharper for Visual Studio -I become the flying dog. In Visual Studio without ReSharper, I was just an ordinary programmer coding projects, unaware of the limits of my productivity. After installing and using ReSharper for Visual Studio, I realized how much more productive I could be:  like 3-5 times more productive. Another analogy might be going to the eye doctor for a routine visit, unaware that your eyesight has deteriorated because you've adapted to having compromised vision without realizing it. "Hey Doc, I see fine!", you tell him. Then you put on the glasses and you see a new world, vivid and crisp. Installing ReSharper is the equivalent of putting on the glasses and realizing you've been handicapped all along.  Although my comments may sound exaggerated, I've gotten the same response from my programmer colleagues over and over again. The benefits of ReSharper can't be overstated when it comes to productivity.

Installation

If you have never used ReSharper and you want to see what I'm talking about, go to the JetBrains website and download the installation. The installation is painless: just run it and it will install itself into Visual Studio. ReSharper is compatible with Visual Studio 2005 SP1 through 2010, so if you are using an older version of Visual Studio you can still take advantage of the accelerated development capability provided by the ReSharper toolset.

1.gif
 
Figure 1 - ReSharper inside of Visual Studio 2010

Although ReSharper is a single product, it's best to think of it as a collection of productivity tools. There are tools inside of ReSharper that allow you navigate seamlessly between your code files. There are also tools for refactoring, generating, fixing and reformatting your code all at the stroke of your keyboard. Speaking of the keyboard, it is wise to learn the shortcut keys in ReSharper because it is quicker than using the mouse. ReSharper enables you to map your keys to a unique set of key combinations, or if you are an IntelliJ user, you can map to IntelliJ keystrokes so you don't get confused between the two key mappings. For those who are not familiar, IntelliJ is ReSharper's Java IDE and it is equally impressive.

In the paragraphs that follow,  I'd like to mention a few of ReSharper's best and most useful tools that make Visual Studio a pleasure to use.

Go To Type/Go To File  (Ctrl  T/Ctrl-Shift T)

If you are new to ReSharper and want to explore the power of navigation, try this utility. If you know the name of your class or even just the primary caps of your class and you want to bring up the file containing it, just hit Ctrl-T and start typing. ReSharper narrows down the class for you. Once you see the drop down, pick the class and start editing your class. ReSharper will also narrow down a file, it doesn't have to be a class.  I find myself constantly editing configuration files. I hit Ctrl-Shift T, type in the first two characters of the config file, and voilà! up comes my file.  Sometimes it feels like ReSharper is reading my mind.  I think it...ReSharper does it. This is especially true when I'm using ReSharper to code my applications:

2.gif
 
Figure 2 -  Go To File Command in ReSharper (Ctrl Shift - T)

You might be saying that you can just use the Navigate To... feature that is part of Visual Studio (a feature that was probably adopted by Microsoft evaluating ReSharper themselves),  but Ctrl T/Ctrl Shift T goes beyond what Navigate To... is capable of.  In ReSharper you can type in a library that is referenced by your project, and ReSharper will find it.  ReSharper also lets you type in either primary caps or lower case humps to find the class, interface, or file you are trying to find.  Using lower case humps is a bit faster than having to mess with the shift key.

3a.gif
 
Figure 3a - Finding a Library Class using ReSharper

3b.gif
 
Figure 3b - Finding a Library Class using just lower case Primary Humps

Generate Code  (Alt  Enter/Alt Insert)

One of the most amazing features of ReSharper is that it codes for you. You may be saying to yourself, "yeah right!"  Well it really...really does.  Here is an example: Create a Customer class by hitting Ctrl-Alt-Insert. You'll be prompted for the class,. Type in the class name Customer.   Click inside the Customer class and choose Ctrl E,L to choose a snippet for a new property name. Of course you could have just as easily typed prop, but this will familiarize you with the snippets.  Now let's look at the real magic:

namespace ConsoleApplication2
{
          public class Customer
          {
                   public string Name { getprivate set; }
          }
}

Click on the Customer class and choose Alt-Insert.  

4.gif
 
Figure 4 - Generate a constructor for the Customer class with a parameter to initialize name

Pick the constructor. ReSharper will prompt you for the variables you want to initialize in the constructor.  We'll choose the Name property and ReSharper will generate all the necessary code for the constructor initialization:

namespace ConsoleApplication2
{
          public class Customer
          {
                   public Customer(string name)
                   {
                             Name = name;
                   }
                   public string Name { getprivate set; }
          }
}

Let's say we coded the Customer class another way.  Perhaps we had a default constructor and we want to add a name property passed into the constructor:

namespace ConsoleApplication2
{
          public class Customer
          {
                   public Customer(string name)
                   {
                   }
          }
}

If we click on the name parameter inside of the constructor and type Alt-Enter we get a menu asking us if we want to create a Name field or property along with a host of other options. It is ReSharper's uncanny  ability to anticipate your every move that makes it a fascinating and valuable tool.  

5.gif
 
Figure 5 - Add an auto property Name from the name parameter in the constructor:

After picking create auto, the following code is generated:

namespace ConsoleApplication2
{
          public class Customer
          {
                   public string Name { getset; }
                   public Customer(string name)
                   {
                             Name = name;
                   }
          }
}

Not only does ReSharper generate the property, it figures out the correct name and casing for the property without the programmer having to type a thing!

Let's say we have a new property we want to introduce, which is called ZipCode, and we want to initialize it in the constructor. Just add the extra parameter zipCode to the constructor:

using System;
namespace ConsoleApplication2
{
          public class Customer
          {
                   public Customer(string name, string zipCode)
                   {
                             Name = name;
                   }
                   public string Name { getset; }
          }
}

Then click on zipCode,type Alt-Enter, and choose initialize auto-property:

6.gif
 
Figure 6 - Create and initialize the Zip Code of the customer

Now we have the following code generated with the new property added and initialized. Although we had to type the word zipCode and define its type, we didn't have to do much else.  This is my general experience with ReSharper: hit Alt-Enter on a piece of code and it generates the code you already imagined in your head only a second ago.

using System;
namespace ConsoleApplication2
{
          public class Customer
          {
                   public Customer(string name, string zipCode)
                   {
                             Name = name;
                             ZipCode = zipCode;
                   }
                   public string Name { getset; }
                   public string ZipCode { getset; }
          }
}

Now let's say I want an interface on my Customer. Let's call it ICustomer:

using System;
namespace ConsoleApplication2
{
          public class Customer : ICustomer
          {
                   public Customer(string name, string zipCode)
                   {
                             Name = name;
                             ZipCode = zipCode;
                   }
                   public string Name { getset; }
                   public string ZipCode { getset; }
          }
}

Click on ICustomer and choose Alt-Enter.  ReSharper will prompt you to create the interface:

7.gif

Figure 7 - Creating an interface in ReSharper for the Customer

using System;
namespace ConsoleApplication2
{
          public class Customer : ICustomer
          {
                   public Customer(string name, string zipCode)
                   {
                             Name = name;
                             ZipCode = zipCode;
                   }
                   public string Name { getset; }
                   public string ZipCode { getset; }
          }
          public interface ICustomer
          {
          }
}

Typically we don't want our interface living inside our class, so we would expect to have to cut the interface, create a new interface in our project, and paste the new interface in the new file. Nope.  ReSharper has a solution for that, too. Click on ICustomer and choose Alt-Enter (notice that key combination again!)  ReSharper will magically create the ICustomer interface file for us, and put it in the project:

8.gif

Figure 8 - Moving an interface to a file using ReSharper 

Another tool you could use is the Extract Interface in ReSharper's refactoring section. Click on Customer:

using System;
namespace ConsoleApplication2
{
          public class Customer
          {
                   public Customer(string name, string zipCode)
                   {
                             Name = name;
                             ZipCode = zipCode;
                   }
                   public string Name { getset; }
                   public string ZipCode { getset; }
          }
}

Go to the ReSharper->Refactor->Extract Interface menu item. Choose the properties you wish to extract into an interface:

9.gif
 
Figure 9 - Generating the customer Interface through Extract Interface

Click Next and again, like magic, ReSharper generates the interface with all the properties you've chosen:

namespace ConsoleApplication2
{
          public interface ICustomer
          {
                   string Name { getset; }
                   string ZipCode { getset; }
          }
          public class Customer : ICustomer
          {
                             public Customer(string name, string zipCode)
                             {
                                      Name = name;
                                      ZipCode = zipCode;
                             }
                             public string Name { getset; }
                             public string ZipCode { getset; }
          }
}

Convenient code generation is prevalent throughout ReSharper. Let's create a method called GetFirstAlias and add a try-catch block. Just by typing try and a TAB key, ReSharper generates the whole try-catch block:

                      int GetFirstAlias()
                      {
                             try
                             {
                             }
                             catch (Exception ex)
                             {
                                      throw;
                             }
                      }

Let's add a new property Aliases to maintain a list of Customer Aliases:

public List<string> Aliases { getset; }


Notice that ReSharper shows us that it doesn't know what a List is yet by highlighting List in Red.  If we hover over the List, ReSharper tells us what it thinks we want, and usually it's right  (There is that mind reading happening again!). Click on List and choose-yup, you guessed it-Alt-Enter, and it resolves the List variable by placing a using statement at the top of the class:

10.gif

Figure 10 - ReSharper Suggesting the Type we need to bring into our class using statement.

If we add a foreach inside of the try block and then tab, we get a list of properties to choose from to loop through:  

11.gif

Figure 11 - Generating a foreach loop with ReSharper.

We choose the Aliases collection and ReSharper generates the block for us. It even makes an intelligent guess at the name of the loop variable:

foreach (var aliase in Aliases)
                                      {
                                      }

What is also intelligent about ReSharper is that it generates the block properly. Notice the use of var for the variable. ReSharper gives the best code for a particular construct. I find myself being reminded of proper coding techniques every time I use the tool.
Method Magic

Let's add a new class called Order by hitting Ctrl-Alt-Insert and typing in the class name Order:

namespace ConsoleApplication2
{
    public class Order
    {
    }
}

Let us add a method to the Customer class to create a new order

public class Customer
{
        public Customer(string name, string zipCode)
        {
            Name = name;
            ZipCode = zipCode;
        }
        public List<string> Aliases { getset; }
        public string Name { getset; }
        public string ZipCode { getset; }
        public void CreateOrder()
        {
            var order = new Order(Name);
        }
}

Of course ReSharper doesn't recognize the new constructor that takes one parameter since we haven't declared it yet. Let's click on the Name parameter in the constructor and hit Alt-Enter:

12.gif
 
Figure 12 - ReSharper creates a Constructor in another class.

ReSharper will generate the code for the constructor in the order class shown below:

using System;
namespace ConsoleApplication2
{
    public class Order
    {
        public Order(string name)
        {
            throw new NotImplementedException();
        }
    }
}

Next, I decide that I want to also pass the zip code as a parameter. Add ZipCode to the parameter passed in the order constructor, click on ZipCode and hit Alt-Enter.  

13.gif
 
Figure 13 - ReSharper changes a Constructor in another class.

ReSharper alters the constructor to now take two parameters and even properly names and the parameters:

    public class Order
    {
        public Order(string name, string zipCode)
        {
            throw new NotImplementedException();
        }
    }

ReSharper has a host of other code generation features including renaming methods and propagating the change to all dependencies, implemented interface method generation, and code completion. Code completion is a really cool feature so let's look at an example.  We can create a LINQ expression for our Aliases to select all Aliases beginning with the letter 'C'.  Start the LINQ expression with:

Aliases.Where();  

Go inside the parenthesis and type Ctrl-Alt-Space for code completion. This will bring up a list of possible completions for the LINQ expression. Typically the best choice is the first one, so we can just hit Enter again:

14.gif

Figure 14 - Using auto-complete inside a LINQ expression

This creates the following partial lambda expression in our LINQ query:

Aliases.Where(s => );       

Now we can just type our predicate after the lambda expression to find aliases starting with C. For our predicate we can use the StartsWith method operating on the string.  Just type s.sw after the lambda and ReSharper will find the StartsWith method leaving your cursor just in the right spot for adding the "C":

15.gif

Figure 15 - Auto Completion of the Predicate in a LINQ Expression


           Aliases.Where(s => s.StartsWith("C"));    

This might not seem like much, but it becomes really useful in all phases of your coding where ReSharper just fills in the blanks for you. Let's create a new event on our Order class called OrderComplete:

    public class Order
    {
        public event Action<string> OrderComplete;
        public Order(string name, string zipCode)
        {
        }
    }

We will subscribe to the event in our Customer CreateOrder method:  

public void CreateOrder()
{
            var order = new Order(Name, ZipCode);
            order.OrderComplete +=
            Aliases.Where(s => s.StartsWith("C"));
}

After typing +=  press Ctrl-Alt-Space to autocomplete our event handler.

16.gif

Figure 16 - Using auto-complete for hooking up an event handler

ReSharper gives us the option of using a lambda expression, a delegate, or a Create method. Let's select the Create method and see what it generates. As if by magic, ReSharper generated the method name for the event handler and the method body itself. Of course we still need to fill in the method body, but the hooking up of the handler is done in a few keystrokes:

         public void CreateOrder()
        {
            var order = new Order(Name, ZipCode);
            order.OrderComplete += OrderOnOrderComplete;
            Aliases.Where(s => s.StartsWith("C"));
        }
        private void OrderOnOrderComplete(string s)
        {
            throw new NotImplementedException();
        }

By having ReSharper suggest coding, you don't need to worry about the details of your code plumbing.  ReSharper already knows what you want.

Inspecting and Fixing Code

If you think that ReSharper is impressive as a code generator, you should see its code repair capability.  Let's bring up one of my old C# classes and take a look through the eyes of ReSharper. I brought in an old project that implements a probability based incremental learning algorithm (PBIL) to determine perfect numbers. Perfect numbers are numbers whose factors produce a sum equal to the product of the factors.  My project contains a class called BinaryGene used to represent a gene of one of the solutions in binary form. If you look at the ReSharper indicator to the right of the scrollbar, it shows us potential problems with this class. Code repair with ReSharper can be anything as simple as changing variables and methods to the proper naming convention to making the code safer for use. A green indicator is a hint, a yellow indicator is a warning, a red indicator is an error (usually a syntax error), and a blue indicator is a suggestion. We have lots of yellow indicators on our indicator bar indicating lots of warnings in our code. Clicking on any of the indicators on the vertical bar brings me to the offending code. Let's go through a few of these warnings:

17.gif
 
Figure 17 - Finding Unused code with ReSharper

ReSharper is really skilled at cleaning up dead code or unused code. The FitPointsToCurve method in my code is in gray, which means it is no longer used. If we click on the method and type Alt-Enter, it comes up with the following choices:

18.gif
 
Figure 18 - Removing Unused code with ReSharper

We can either remove it or comment it out. Since we are not using it, we'll choose to remove it. Once we make our choice, ReSharper removes the stagnant code from our file and also the nasty little yellow mark on the indicator bar.   Once all those marks are gone, ReSharper alerts us by putting a green indicator at the top of the indicator bar. 
 
Let's eliminate the yellow marks one at a time by navigating to each of them using Alt-Page Down and clicking Alt-Enter on all the squiggly marked code fragments. You'll want to do this one by one, because you might not agree with ReSharper's assessment of your code. I would say ReSharper is right 99% of the time.

At the top of my class I noticed a blue line under some of my constants. That is because my constant naming convention doesn't match the one shown in ReSharper. ReSharper chooses a standard naming convention for C#, but if yours varies slightly you can change it:

19.gif
 
Figure 19 - Detecting Code Not Following the Naming Convention

If you want to keep the naming convention you already have in your code as upper case, go to ReSharper->Options->C# Naming Style. 

20.gif
 
Figure 20 - Naming Convention Rules in ReSharper Options Dialog

Go to Constant fields not private and choose ALL_UPPER.  

21.gif
 
Figure 21 - Changing Naming Convention Rule for Constants

This will remove the blue marks from all the constants with this naming convention:

public const int LENGTH = 100;
public const double LEARNING_RATE = .005;

I learned after talking to the JetBrains folks that this is the long way to change the naming convention of a constant.  As with a lot of utilities in ReSharper, all I needed to do was click on the constant name and hit (you guessed it) Alt-Enter. Then I could choose Change settings for naming rule 'Constants fields (private)' to accomplish the same thing in a fraction of the time:

22.gif
 
Figure 22 - The Easy Way to Change the Naming Rule for Constants

You can tell that the JetBrains guys must have read Robert Martin's book, Clean Code, because they have best practices suggested all over the place for making your code cleaner and more readable. In the following code, in figure 23, I have the declaration for nextNumber:

23.gif

Figure 23 - ReSharper Detects far away declarations

ReSharper offers to move my variable closer to the code that uses it. Hitting Alt-Enter moves the code closer to the place where it is used:

          for (int i = 0; i < LENGTH; i += NUMBER_SIZE)
                             {
                                      int nextNumber = FormNumber(i, NUMBER_SIZE);
                                      if (nextNumber == 1)
                                      {
                                                oneThere = true// always need a one.
                                                moreThanOneOne++; // don't want more than one 1
                                      }

ReSharper also finds problems with comments in your code.  Here I have a parameter in my comment that is not even used by the code:

24.gif 

Figure 24 - Bad Comment Found by ReSharper

ReSharper even detected an error while I was writing this article, as seen in figure 25. You cannot compare a double value to a NaN with an equality operator without getting a false return value:

25.gif
 
Figure 25 - Bad Comparison found by ReSharper

Apparently you need to use the code listed below to compare a double to NaN (Not a Number):

                             if (double.IsNaN(product))
                             {
                                      _fitness = -100000;
                             }

Refactoring in ReSharper

If at any time you need to refactor code in ReSharper,  just select the piece of code that you wish to refactor and hit Ctrl-Shift-R.  ReSharper will automatically figure out which refactor options you can choose from.  Notice that we have embedded constant of -100000 in the code in our last example. If we click on the constant value and choose Ctrl-Shift-R, it gives us a list of choices for refactoring the number:

26.gif

Figure 26 - Refactoring the Embedded Constant using Ctrl-Shift-R

If we pick introduce field, a dialog comes up with a bunch of refactoring options for the field.  We want to make -100000 a constant, so we choose constant and give it a name:

27.gif
 
Figure 27 - Refactoring the Embedded Number into a Constant in the Class

ReSharper will change the value of -100000 to a constant and declare the constant at the top of the class.

        private const int EXTREMELY_NEGATIVE_NUMBER = -100000;
        ...
          if (double.IsNaN(product))
            {
                _fitness = EXTREMELY_NEGATIVE_NUMBER;
            }

Reformatting the Code

After refactoring my code, I want to make it look pretty. Choosing Tools->Clean Up Code or Ctrl E + Ctrl C, reformats the code and makes it readable. When you select this feature you are given the option of a full cleanup or just a reformat of the code. (It's a little like going to the carwash and getting a choice of a wash or a wash and a wax!). A full cleanup does more than remove redundant white spaces. It actually changes the code itself to be more readable. Figure 28 shows some of the things ReSharper will do, like use var where appropriate, remove unused using directives, make certain fields read only, and more. They are pretty benign changes, but be careful when using this option. The other thing you want to be mindful of is that if you are using source control and you reformat your code, it might be difficult to compare changes you've made to the previous version.  But in general, this is a great feature; it makes your coding look more professional and is an easy way to impress others working with your code:

28.gif
 
Figure 28 - Reformatting and General Clean Up Utility in ReSharper

Using ReSharper in Silverlight

Although ReSharper doesn't work with every language in .NET (It doesn't work with Visual C++ for example), it does work to some extent with XAML. I take advantage of ReSharper whenever coding up XAML. If you add a control that doesn't have a namespace declaration at the top of your file, hitting Alt-Enter on the control will automatically add the namespace for you. This is a real time saver when you are coding up XAML by hand.

Using ReSharper in ASP.NET

If you are a web developer using .NET technology, then ReSharper can help you both in your C# server-side code as well editing your mark-up.  For example, ReSharper can do code completion on your server tags.  If you are an ASP.NET MVC programmer, then you are going to love the coding assistance ReSharper provides for inline code in your web pages.  If you are curious about some of the features that ReSharper brings to the table for web development check out ReSharper's ASP.NET feature list for the Visual Studio editor.  JetBrains has also told me that they will soon come out with support for both JavaScript and CSS which is a boon for web developers coding for any platform: 

Conclusion

ReSharper is an award winning product. I have not encountered any problems with it and have reaped its many benefits. As of this writing, a personal license for C# runs about $149, and a commercial license is $249. If you are a professional developer and want to greatly improve your coding experience in Visual Studio, buying ReSharper is a no-brainer. If you want to resharpen your coding skills and make your code more readable, more maintainable and less prone to error, then do yourself a favor and download it and give it a whirl.

Up Next
    Ebook Download
    View all
    Learn
    View all