Skip to content

Setup StyleCop for .NET Core project

StyleCop is awesome tool for big, long running projects where coding style should be congruent. It’s easier to let tool check for naming convention, amount of empty lines and empty catch blocks, than go through these things all the time in code reviews.

In history StyleCop was run with it’s own Visual Studio plugin, but now when .NET can be written in Visual Studio Code, Visual Studio or in almost any editor, it’s not a valid option.

 

Add StyleCop to existing .NET Core project

First add StyleCop.Analyzers nuget package to all the projects that should be under style checking. Nuget packages can be also managed at solution level where its easier to setup for multiple projects.

Thats it. Now when project is build all the styling problems are reported as warnings, but what if we want to convert warnings into errors and block build if it does not contain valid styling? Well things get bit trickier…

First we need to tell our .NET core project that it should use custom ruleset file. So add following line into projects PropertyGroup tag

<CodeAnalysisRuleSet>CustomCodeAnalysisRules.ruleset</CodeAnalysisRuleSet>

Then create new file in projects root folder with name
CustomCodeAnalysisRules.ruleset

Or if analyzer should use one ruleset for whole solution, add ../ in front of CustomCodeAnalysisRules.ruleset file name and add ruleset file into parent folder.

Add following example ruleset to add compile error from double semicolons:

<?xml version="1.0" encoding="utf-8" ?>
<RuleSet Name="StyleCop rules for Core Application" Description="Custom Rules" ToolsVersion="10.0">
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.CSharp.ReadabilityRules">
    <Rule Id="SA1107" Action="Error" />
  </Rules>
</RuleSet>   

Now its easy to test build failuring by adding extra semicolon after any line.