Clean C# via SyleCop

StyleCop is an open source source code analysis tool that can check your C# code against a predefined set of style rules published by Microsoft.  When working in C# I find this tool is a great asset for helping me achieve the rule of “Leaving the code in a better state than when you first started working on it”. It only helps with identifying style issues in the code, which is only a single aspect of “clean code”, but it can be great for helping teams enforce consistent style.

Another caveat is that while all these rules might be great for organizations like Microsoft, they are probably overkill in some areas and some even seem to go against maintainability and readability. Regardless, the rules provide a solid base to start with, which can prevent teams from spending too much time debating matters of coding style.

Here is the StyleCop settings file I use on my C# projects, disabling a few rules:

<StyleCopSettings Version="4.3">
<Parsers>
<Parser ParserId="Microsoft.StyleCop.CSharp.CsParser">
<ParserSettings>
<BooleanProperty Name="AnalyzeDesignerFiles">False</BooleanProperty>
</ParserSettings>
</Parser>
</Parsers>
<Analyzers>
<Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.OrderingRules">
<Rules>
<Rule Name="UsingDirectivesMustBePlacedWithinNamespace">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules">
<Rules>
<Rule Name="DocumentationTextMustMeetMinimumCharacterLength">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="ConstructorSummaryDocumentationMustBeginWithStandardText">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
<Rule Name="FileMustHaveHeader">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
<Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.ReadabilityRules">
<Rules>
<Rule Name="PrefixLocalCallsWithThis">
<RuleSettings>
<BooleanProperty Name="Enabled">False</BooleanProperty>
</RuleSettings>
</Rule>
</Rules>
<AnalyzerSettings />
</Analyzer>
</Analyzers>
</StyleCopSettings>

I find it very useful to run StyleCop before I commit some code, often it will show me things I just simply overlooked because I was too focused at the task at hand. This tool also works well with FxCop, even though there is a little overlap in some areas.

Headshot

Hi there, I'm Seth Deckard, a software developer with years of experience working in Ruby and Rails. I co-founded WarningAware and have authored several open source projects on GitHub. You can reach me on Twitter.