Press "Enter" to skip to content

Using ReSharper for clean and consistent C# code

This guide will show you how to use ReSharper to keep your code clean and consistent – and easy to work with.

 

Video version here

 

Importance of clean and consistent code

Professional cooks follow a practice of “clean as you go”. It’s also one of the 5S practices in Lean methodologies.

With a clean work space, it’s easier to do future work.

This is also a good practice to follow in programming. With “clean” code, it’s easier to know what the program is doing – which makes it simpler to fix bugs and faster to make modifications and enhancements.

 

One tool I use to keep my code clean and consistent is ReSharper.

ReSharper helps with refactoring code. But, it also lets you define your coding standards – variable name rules, layout of your class files, position of curly braces, etc.

You can even create multiple coding standard profiles, in case you work on projects with different standards – for example, open source projects, or if you consult for multiple companies.

 

When your classes look like a disorganized desk drawer, it takes longer to find what you’re looking for. Keeping code clean and consistent probably saves me fifteen to thirty minutes per day, and eliminates a huge amount of frustration.

 

Setting up your source code standards

After you install ReSharper, you’ll see a new “ReSharper” menu option in Visual Studio.

To configure your coding standards, click on ReSharper -> Options…

 

In the Code Inspection -> Settings screen, check “Enable code analysis”

 

Select Code Inspection -> Inspection Severity, to set the level of severity for the different rules (there are around 100 of them). You can set them to: Do not show, Hint, Suggestion, Warning, Error – depending on how important the rule is to you.

 

Under Code Editing -> Code Cleanup, choose your profile, and select what rules you want applied when you tell ReSharper to clean your code (by clicking Ctrl-E+C).

 

Also, in the Code Editing section, select the language you work with. This is where you can configure the rules about variable names (in Naming Style), code formatting (spaces, curly brace placement, blank lines, etc.), how you want to organize your class files (placing the private variables, constructors, methods, etc. in specific positions), and other rules in the Code Style section.

 

Sample class (before cleaning)

Here is a class that has not been cleaned. It has unneeded “using” statements, is in the wrong namespace, doesn’t follow any naming standard, and has unused variables.

To clean it, you click on Ctrl-E+C, and ReSharper will show a popup, asking which coding standard profile you want to use. After selecting one, the code will look like it does in the next section.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Engine.BusinessObjects
{
    public class Account
    {
        public Account(int Id, string customerNAME)
        {
            ID = Id;
            CustomerName = customerNAME;
        }
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }
        private int _id;
        public string CustomerName { get; set; }
        public DateTime openDate { get; set; }
        public void AddMoney(decimal AmOuNt)
        {
            _balance += AmOuNt;
        }
        public const decimal interest_rate = 0.01M;
        public decimal _balance { get; set; }
        public void WithdrawMoney(decimal AMOUNT)
        {
            var balanceAfterWithdrawal = _balance - AMOUNT;
            var isOverDraft = balanceAfterWithdrawal > 0 ? true : true;
            if(AMOUNT < 0)
                throw new ArgumentOutOfRangeException();
            if(AMOUNT > _balance) throw new ArgumentOutOfRangeException();
            _balance -= AMOUNT;
        }
    }
}

 

Sample class (after ReSharper cleanup)

This code has been cleaned, but still has some coding standards warnings. With ReSharper, these are shown with a blue squiggly line underneath the problem variables and methods.

You correct them by clicking on the variable (or property or method) and clicking Alt-Enter, or clicking on the light bulb symbol in the left column of the editor. ReSharper will show its suggested correction. If you select the correction, it will update any code that uses that variable/property/method – so you don’t need to make the correction in other classes.

After making these corrections, the code will look like it does in the next section.

using System;
namespace Engine.BusinessObjects
{
    public class Account
    {
        public const decimal interest_rate = 0.01M;
        private int _id;
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }
        public string CustomerName { get; set; }
        public DateTime openDate { get; set; }
        public decimal _balance { get; set; }
        public Account(int Id, string customerNAME)
        {
            ID = Id;
            CustomerName = customerNAME;
        }
        public void AddMoney(decimal AmOuNt)
        {
            _balance += AmOuNt;
        }
        public void WithdrawMoney(decimal AMOUNT)
        {
            decimal balanceAfterWithdrawal = _balance - AMOUNT;
            bool isOverDraft = balanceAfterWithdrawal > 0 ? true : true;
            if(AMOUNT < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if(AMOUNT > _balance)
            {
                throw new ArgumentOutOfRangeException();
            }
            _balance -= AMOUNT;
        }
    }
}

 

Sample class (after applying ReSharper hints)

This is the final, clean version of the class. Unused code has been removed, making it smaller, and easier to search through. The variables/properties/methods use a consistent naming standard. And, the “if” statements follow my preferred standard.

Now, if I need to find a bug in this class, it should take less time. If I need to modify this class, to add a new feature, it will be easier to make the modification.

using System;
namespace Engine.Models
{
    public class Account
    {
        public const decimal INTEREST_RATE = 0.01M;
        public int ID { get; set; }
        public string CustomerName { get; set; }
        public DateTime OpenDate { get; set; }
        public decimal Balance { get; set; }
        public Account(int id, string customerName)
        {
            ID = id;
            CustomerName = customerName;
        }
        public void AddMoney(decimal amount)
        {
            Balance += amount;
        }
        public void WithdrawMoney(decimal amount)
        {
            if(amount < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if(amount > Balance)
            {
                throw new ArgumentOutOfRangeException();
            }
            Balance -= amount;
        }
    }
}

 

 

My ReSharper profile

Here is a copy of the profile I use: download link.

I think this is a good set of coding standards (obviously). It’s configured to make the code as “obvious” as possible. However, if you don’t like one of the rules, you can always change it to something you prefer.

 

Purchasing ReSharper

Before looking at the price, JetBrains does have discounted, and free, licenses available. If you are a startup, student, teacher, maintain an open source project, or a few other conditions, you might qualify. Visit this page, to see.

ReSharper is available through an annual subscription. Personally, I don’t like subscription software. But, ReSharper is extremely useful to me, so I pay for it.

 

A personal license for ReSharper costs $129 for the first year. If you continually maintain your subscription, the annual fee gets lower – $103 the second year, $77 the third year and onwards.

There is also a ReSharper Ultimate subscription. This includes ReSharper, dotTrace (a performance profiler), dotCover (a tool to see how much of your code is covered with unit tests), and dotMemory (to profile a program’s memory use).

 

Disclaimer

I did not receive anything from JetBrains for this article. I am not an affiliate. I wasn’t paid for this post. I pay for my personal ReSharper subscription with my own money.

2 Comments

  1. Kevin
    Kevin July 29, 2017

    Hello Scott!

    Thanks for all your impressive work through your articles 🙂

    I learned a few useful things about ReSharper that I wasn’t aware of.
    But something you forgot to mention is the fact that ReSharper ultimate is available for free for students in IT courses, as long as they can provide an academic email address (their school’s admins have to execute a small procedure to be recognized by Jet Brains website).
    And while I’m at it, thank you so much for your great series about design patterns! You cannot imagine how much time you saved me 🙂

    By the way, it would be great too, if you make the same about unit testing. Any plans about this topic?

    Have a nice day and keep up the good job!

    Kevin

Leave a Reply

Your email address will not be published. Required fields are marked *