Software Development

Maintain code consistency with Microsoft StyleCop

A consistent coding standard simplifies the chore of code maintenance. Find out how StyleCop helps make this possible if you're using C# and Visual Studio 2008/2010.

One of the most demanding aspects of a developer's life is working with legacy code created by others who may not share your philosophy on code creation. Code consistency is beneficial to both the team and the organization, with the added benefit of improving performance through rules such as closing database connections. Microsoft StyleCop provides the vehicle to put such rules in place, and it seemlessly integrates with Visual Studio 2008/Visual Studio 2010 and MSBuild to make sure everybody is on the same page.

(Note: StyleCop should not be confused with FxCop. StyleCop works with source code, whereas FxCop works with compiled files.)

Getting it

StyleCop is freely available from its CodePlex site; the current version is 4.4 with 4.5 in beta. The current versions only work with C#. The site contains the following downloads:

  • StyleCop installer -- An MSI file that installs the StyleCop components on your system.
  • Rules documentation -- A Microsoft Help file that contains details of StyleCop rules included with the install, as well as how to suppress rules.
  • StyleCop SDK -- The StyleCop software development kit, which provides information on creating your own rules to use with the tool.

What is installed?

Installation is as easy as point and click with the StyleCop download. Once downloaded, run the MSI file. During installation, the StyleCop tool provides the option to integrate with your Visual Studio 2008 or Visual Studio 2010 installation, along with the necessary files installed in the C:\Program Files\Microsoft StyleCop 4.4.0.14. The version number in the path will vary depending on the version installed. This directory contains the product dll files (Microsoft.StyleCop.CSharp.dll, Microsoft.StyleCop.CSharp.Rules.dll, Microsoft.StyleCop.dll, and Microsoft.StyleCop.VSPackage.dll) along with Settings.StyleCop and StyleCopSettingsEditor.exe. The beta version promises Visual Studio templates, as well as a ReSharper plugin.

Choosing rules

The StyleCopSettingsEditor.exe is a utility that allows you to view the rules installed and enabled. It is run from a command line with the settings file passed to it, as the following line demonstrates with the results of running it displayed in Figure A:

StyleCopSettingsEditor.exe Settings.StyleCop

Figure A

The StyleCop administrative interface for viewing and enabling rules. (Click the image to enlarge.)
The administrative interface in Figure A can be used to enable or disable rules. Figure B shows the rule specifying that a blank line must follow a closing curly brace -- it is unchecked and thus disabled, so it will be ignored when StyleCop executes on source code. Figure B

The StyleCop administrative interface with curly brace rule disabled. (Click the image to enlarge.)

Visual Studio integration

The StyleCop installation adds new Visual Studio options to run StyleCop on source code/projects open in Visual Studio. The following options (Figure C) are available via the Tools menu:
  • Run StyleCop -- Runs the StyleCop utility on all code in current solution. The results (any errors) will appear in the normal error list window.
  • Run StyleCop (Rescan All) -- Reruns the StyleCop utility on all code in the current solution.
Figure C

The StyleCop options available in Visual Studio. (Click the image to enlarge.)

The StyleCop options are also available for individual items like code files via the Context menu (right-clicking on the item). This allows you to process items at a granular level. The Context menu for a project adds one more option -- StyleCop Settings. This allows you to access the previously discussed StyleCop administration window shown in Figure B.

StyleCop in action

The following basic program will be used to demonstrate how StyleCop works with C# code; it contains a simple class for person data. Two instances of this class are created and populated with the details output via the console.

namespace StyleCopTest

using System;

/// <summary>

/// Basic class to hold Person data

/// </summary>

class Person

{

/// <summary>

/// Person class constructor

/// </summary>

/// <param name="pFirstName">Person first name</param>

/// <param name="pLastName">Person last name</param>

/// <param name="pMiddleName">Person middle name</param>

/// <param name="pOccupation">Person occupation</param>

public Person(string pFirstName, string pLastName, string pMiddleName, string pOccupation)

{

this.FirstName = pFirstName;

this.LastName = pLastName;

this.MiddleName = pMiddleName;

this.Occupation = pOccupation;

}

/// <summary>

/// Default Person class constructor

/// </summary>

public Person()

{

}

public string FirstName { get; set; }

public string LastName { get; set; }

public string MiddleName { get; set; }

public string Occupation { get; set; }

}

}

namespace StyleCopTest

{

using System;

/// <summary>

/// Test program for working with StyleCop

/// </summary>

class Program

{

static void Main(string[] args)

{

Person p1 = new Person("Ryan", "Howard", String.Empty, "First baseman");

Person p2 = new Person();

p2.FirstName = "Roy";

p2.LastName = "Halladay";

p2.MiddleName = String.Empty;

p2.Occupation = "Pitcher";

Console.WriteLine(p1.Occupation + " : " + p1.FirstName + " " + p1.LastName);

Console.WriteLine(p2.Occupation + " : " + p2.FirstName + " " + p2.LastName);

}

}

}

Once the code is entered and compiled, I select Tools | Run StyleCop to process the code against the standard StyleCop rules. Figure D shows the results of this process. Figure D

The results of running StyleCop against the sample code. (Click the image to enlarge.)

The following list provides a sampling of the errors generated in Figure D. The lines have been edited for readability, but they basically give you the error message followed by the class that contained the error and error location (line and column numbers).

  1. An opening curly bracket must not be followed by a blank line. Person.cs  9  1
  2. A closing curly bracket must not be preceded by a blank line. Person.cs  31  1
  3. The class must have an access modifier. Program.cs  7  1
  4. The property must have a documentation header. Person.cs  31  1
  5. The variable name 'pFirstName' begins with a prefix that looks like Hungarian notation. Remove the prefix or add it to the list of allowed prefixes. Person.cs  17  1

The first error states that an opening curly bracket must not be followed by a blank line as the code contains in the Person class. The second error states the closing curly brace must not be preceded by a blank line. The third error states that the Program class must have an access modifier. The fourth error states that the properties in the Person class must have documentation headers.

The fifth error is interesting as it states that the variable name (pFirstName in this case) appears to use Hungarian notation but not according to what is acceptable by StyleCop. We can easily fix this by editing the Settings.StyleCop file in the StyleCop default directory. It is an XML file that contains a Hungarian collection that defines what prefixes are acceptable for Hungarian notation. We can simply add entries to this list to avoid the error message received. The following listing shows this file with my entry (p) added in bold.

<StyleCopSettings Version="4.3">

<Analyzers>

<Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.NamingRules">

<AnalyzerSettings>

<CollectionProperty Name="Hungarian">

<Value>as</Value>

<Value>do</Value>

<Value>id</Value>

<Value>if</Value>

<Value>in</Value>

<Value>is</Value>

<Value>my</Value>

<Value>no</Value>

<Value>on</Value>

<Value>to</Value>

<Value>ui</Value>

<Value>p</Value> </CollectionProperty>

</AnalyzerSettings>

</Analyzer>

</Analyzers>

</StyleCopSettings>

Now, all of these errors correspond to rules defined in StyleCop. If you have no worries about the curly bracket errors, then you can disable them within StyleCop to avoid the error message.

Extending the tool

While StyleCop is a great tool, it can be extended to better integrate with your organization. The StyleCop SDK allows you to create our own rules to fit your needs. For example, you may create a rule that ensures all try blocks have a corresponding finally block or even make sure that all database connections open are properly closed. These rules can be created by creating your own class and extending the StyleCop SourceAnalyzer class. More information is available in the SDK available for download.

Consistency and conformity

Code readability and manageability are not big issues when working solo, but as the development team grows so does the issues related to managing a code base. A consistent coding standard simplifies the chore of code maintenance, and StyleCop provides this ability, as well as allows you to add your own rules to further enforce standards.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

1 comments
mjavadi
mjavadi

I am trying to run StyleCopCLI from the command line. It works fine on my local machine but if I map a network drive or run it from the network, it fails (shows the bogus no violation encountered message). D% D:\stylecopcli\StyleCopCLI.exe -cs D:\test\Enumerations.cs Pass 1: Enumerations.cs 238 violations encountered. D% \\devl-scr\scratch\stylecopcli\StyleCopCLI.exe -cs D:\test\Enumerations.cs No violations encountered

Editor's Picks