Click here to Skip to main content
15,400,390 members
Articles / Web Development / ASP.NET
Posted 6 Nov 2008


123 bookmarked

C# Code Reviews using StyleCop – Detailed Article

Rate me:
Please Sign up or sign in to vote.
4.64/5 (36 votes)
6 Nov 2008CPOL5 min read
This is a detailed article on C# code reviews using StyleCop

Table of Contents


In this article, we will discuss an upcoming code review tool StyleCop. We will understand the basics and do a small sample of code review practically to understand how StyleCop works.

You can read my previous article on code reviews using FXCOP.

Installing and Download StyleCop

StyleCop analyzes C# code with a set of rules to check whether the code follows the rules. You can download StyleCop from this link. If you click on the downloads section, you will see three setups, one is the StyleCop setup which actually installs the software and the other two are CHM help files. One help file talks about the rules and the other about the API exposed by StyleCop.

Once you install StyleCop, nothing will be seen as in start menu. When you open any project of C# and right click on the project, you should see two menus in the project as shown in the figure below - one which helps us select the rules, i.e. the Stylecop settings menu and the other which runs these rules on the C# project.

Image 1

If you just run the stylecop, you should see broken rules in output window as shown in the figure below:

Image 2

Comparing FXCOP with StyleCop

FXCOP StyleCop
It runs on compiled DLLs. It runs on actual source code.
As it runs on compiled IL code it can be used for C#, VB.NET, in short any language which compiles to IL code. Currently it runs only on C#.

Currently, I can only think about two differences. If any one knows more, let me know so that I can update this. Many people are asking for a comparison table for these two codes review tools. 

Issue of Code Review using FXCOP

First, let me thank Thomas Wellar for giving me accurate information about FXCOP issues with code review.

FXCOP works on the actual compiled DLL. For instance, a switch method shown below can be compiled to dictionary of string by the .NET compiler. Due to this, we cannot actually measure what kind of quality the code has. The conversion from actual source code to IL is very much non-linear. This is where StyleCop has an extra edge as it operates directly on the source code. The only negative point it has currently is that it only works for C#.

Image 3

StyleCop Code Parsing Logic

StyleCop has two important concepts - one is the document and the other the elements. Document is the file and elements are everything inside the file.

Image 4

For instance, below is a simple source code which has two methods, properties and variables.

Image 5

So stylecop treats everything inside the document as an element. Now let’s understand how stylecop browses through the document by implementing a custom rule in stylecop.

Image 6

Making the Custom Rules Class

The first thing is to import stylecop namespaces. Please ensure that you give references from c:\Program files\Microsoft Style Cop folder.

using Microsoft.StyleCop.CSharp;
using Microsoft.StyleCop;

All stylecop custom rule classes should inherit from SourceAnalyzer class: 

public class MyRules : SourceAnalyzer

When the style cop starts running, it first hits the analyzedocument method. So override the method and let’s put our logic in this:

public override void AnalyzeDocument(CodeDocument document)

In the analyze document, we type cast the document into CsDocument class. As we had previously said, stylecop walks through the document and then walks through each element. This it achieves by using delegates and visitor pattern. The WalkDocument method visits the VisitElement for every element in the source code. In case you are curious about visitor pattern, you can always read the same from this article.

CsDocument document2 = (CsDocument)document;
if (document2.RootElement != null && !document2.RootElement.Generated)
document2.WalkDocument(new CodeWalkerElementVisitor<object>
				(this.VisitElement), null, null);

The VisitElement defined in the WalkDocument method is a delegate. So we need to also define that delegate. You can see in the below code how we have defined the delegate and used the element object to check whether it's a method or not. If the element is a method, then you can perform some logic. If there is any violation, we need to add the same to the violation collection using AddViolation method as shown in the below snippet: 

private bool VisitElement(CsElement element, CsElement parentElement, object context)
if (element.ElementType == ElementType.Method)
{ this.AddViolation(parentElement, "MyCustomRule", "BlockStatementsShouldNotBeEmpty");

One of the values we pass to the rule is MyCustomRule value. This is nothing but the XML file. Below is a sample of a GOTO sample rule. When you compile the DLL, you need to ensure that this XML file is compiled as an embedded resource.

<SourceAnalyzer Name="Custom Rules">
<Description> Custom rules added to analyzer. </Description>
<RuleGroup Name="Database">
<Rule Name="MyCustomRule" CheckId="HE3333">
<Context>Always close the connection object</Context>
<Description>Always close the connection object</Description>

Image 7

Once you have compiled the DLL, you need to put the DLL in the “C:\Program Files\Microsoft StyleCop 4.3\” folder. If everything is fine, you should see the rules in the rules dialog box as shown in the figure below:

Image 8

Let Us Do Something Practically

So let’s take up something practically. Let’s say we want to check if any connection object is opened, it should be closed. So let’s write some good logic in the VisitElement delegate.

The first thing we will do is define two variables - boolFoundConnectionOpen which states that the connection object is opened and boolFoundConnectionClosed which indicates that the connection object is closed. 

bool boolFoundConnectionOpen=false;
bool booFoundConnectionClosed=false;

In the VisitElement delegate, we type cast the element document into CsDocument type and read the source into a TextReader.

CsDocument document3 = (CsDocument)element.Document;
System.IO.TextReader objReader = document3.SourceCode.Read(); 

Ok, now we look through the reader object and start reading the code. If we find a “.Open”, we set the boolFoundConnectionOpen to true. If we find a corresponding close, we set boolFoundConnectionClosed to true.

while ((strCode = objReader.ReadLine()) != null)
if (strCode.Contains(".Open();"))
boolFoundConnectionOpen = true;
if (strCode.Contains(".Close();"))
booFoundConnectionClosed = true;

Now the final thing. If we find that the connection is open and not closed, we just add to the violation collection the rule.

if ((boolFoundConnectionOpen) && (booFoundConnectionClosed==false))
this.AddViolation(parentElement, "MyCustomRule", "BlockStatementsShouldNotBeEmpty");

Run and enjoy… You can see in the below figure that we do not have a connection closed. You can see how the error is displayed in the output window.

Image 9

For Further reading do watch  the below interview preparation videos and step by step video series.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

GeneralUnable to create rule Pin
Yogeshwari Jadhav19-Apr-11 0:07
MemberYogeshwari Jadhav19-Apr-11 0:07 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen6-Apr-11 23:37
professionalSunasara Imdadhusen6-Apr-11 23:37 
GeneralQne question Pin
Brij17-Aug-09 5:26
mentorBrij17-Aug-09 5:26 
GeneralVery useful. Thanks Pin
jack48529-Jun-09 10:42
Memberjack48529-Jun-09 10:42 
GeneralThanks Pin
chunchun200526-Mar-09 7:04
Memberchunchun200526-Mar-09 7:04 
QuestionHow to debug stylecop custom Rule? Pin
naveen.gundu8-Feb-09 23:25
Membernaveen.gundu8-Feb-09 23:25 
AnswerRe: How to debug stylecop custom Rule? Pin
Hari.net18-May-09 19:19
MemberHari.net18-May-09 19:19 
Generalgood article Pin
Donsw7-Feb-09 11:57
MemberDonsw7-Feb-09 11:57 
Questionaspx pages Pin
akume3252-Feb-09 16:14
Memberakume3252-Feb-09 16:14 
QuestionFxCop can be replaced by StyleCop? Pin
Rajesh KS28-Jan-09 22:58
MemberRajesh KS28-Jan-09 22:58 
GeneralUseful Pin
Abhijit Jana19-Nov-08 19:34
professionalAbhijit Jana19-Nov-08 19:34 
GeneralPretty useful. Pin
Rajesh Pillai11-Nov-08 20:57
MemberRajesh Pillai11-Nov-08 20:57 
GeneralLiked it Pin
Bnaya Eshet10-Nov-08 9:21
MemberBnaya Eshet10-Nov-08 9:21 
GeneralGood Work. Pin
Pramod Pallath Vasudevan7-Nov-08 1:16
MemberPramod Pallath Vasudevan7-Nov-08 1:16 
GeneralCode styling Pin
Hristo-Bojilov6-Nov-08 22:23
MemberHristo-Bojilov6-Nov-08 22:23 
GeneralGood one...India ka naam roshan kar raha hai Pin
Sadadevguru6-Nov-08 20:55
MemberSadadevguru6-Nov-08 20:55 
GeneralNice Pin
Paul Selormey6-Nov-08 20:44
MemberPaul Selormey6-Nov-08 20:44 
JokeRe: Nice Pin
Shivprasad koirala6-Nov-08 20:50
MemberShivprasad koirala6-Nov-08 20:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.