We use StyleCopAnalyzers (the successor of the StyleCop package) to get consistent code in all our projects. While it is sometimes annoying, it is the simplest way we found to enforce code style guidelines. Since we use it in all our projects, we want to reuse our customised ruleset.
StyleCopAnalyzers allows you influence the rules with a stylecop.json file. We have one stylecop.json per solution and add it to all our projects as a link. Unfortunately, due to a bug in Roslyn there is some extra work you must do or your customised rules will not work.
First, install the NuGet package StyleCop.Analyzers into your project:
1 |
Install-Package StyleCop.Analyzers |
Then add the stylecop.json file as a link to the root of your project.
If you have a .Net Standard project, you need to set the Build Action for the stylecop.json file to C# analyzer additional file:
If you have a .Net Full Framework project, you need to set the Build Action to AdditionalFiles:
With this little change StyleCopAnalyzers will use the correct set of rules and enforce them.
Update 29 September 2020
Visual Studio moves fast, and it seems as one of the last versions broke the integration of StyleCop. With a few additional tweaks we can get StyleCop back to work.
For .Net Standard projects you may need to add this snipped to the *.csproj
file (right above the ItemGroup with the stylecop.json entry) – do not forget to change the path:
1 2 3 |
<PropertyGroup> <CodeAnalysisRuleSet>$(SolutionDir)\StyleCopRules\YourStyleCopFile.ruleset</CodeAnalysisRuleSet> </PropertyGroup> |
For the .Net Full Framework you best turn on the build option “TreatWarningsAsErrors” and right below that line in the *.csproj
file you add this – again, do not forget to change the path:
1 |
<CodeAnalysisRuleSet>..\StyleCopRules\YourStyleCopFile.ruleset</CodeAnalysisRuleSet> |
This change worked for me in VS 16.7.3.
Amazing! Thank you!