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.

I have been writing and recording videos on architecture, design patterns, UML, enterprise blocks, estimation, and code reviews. You can view all my videos here. If you have any feedback, do email me at shiv_koirala@yahoo.com.

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.

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

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#.

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

publicoverridevoid 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.

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:

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.

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

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:

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.

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.

You are doing excellent job for the entire IT professionals community.I found your FAQs very fruitful.

I have few questions that I faced in my interview(Might be this is not related to article).Can you xplain them in bit detail when you get time.
- Diff between passing an object and reference of an object to a Method?
- When we create an object as A objA=new A(); what all happens in memory?
- Can we manually increase the size of managed heap (GC)?

Hi,
Could anyone help me in debugging the StyleCop custom rule? I have written a rule which actually finds any private variables which doesn't starts with "m_". But its showing all the private variables violating this rule irrespective of whether they are starting with "m_" or not?