.NET Core projects with StyleCop Analyzers

Different developers have different coding styles, however when you work as a team you want to make sure everyone can quickly pick up any part of code and could get their head around in no time. For this reason, it’s great when code has unified style. This can be done manually (not recommended :)) or by using code analyzers in Visual Studio. Default set of rules check for the most common issues, however do not keep the coding style itself unified. Therefore, such tools like StyleCop Analyzers become really handy in such cases.

StyleCop Analyzers is a successor of StyleCop and uses built-in Visual Studio analyzers functionality, therefore works fast, highlights issues as you type, and shows them as warnings in Visual Studio. Let’s try to set up this for the latest .NET Core platform.

StyleCop Analyzers comes as a nuget package:

Install-Package StyleCop.Analyzers -Version 1.0.0-alpha001 -Pre

Once it’s installed basically you are all set to start working.

.NET Core compatibility. While all features are supported you will probably notice that issues highlight doesn’t work as you type, you have to compile code to get warnings displayed. Also, settings and rules editing might be so user-friendly as in a standard .NET application, since you have to modify project.json file manually.

A few tips and tricks:

  • Make warnings to be treated as errors, and this will force your colleagues to follow the same coding style guidelines.
  • You might want to disable some rules, e.g. I always disable suffixing fields with this, since this way it doesn’t contradict ReSharper.
  • Rules set can be extracted outside your project to have a single rules set per solution. This can be achieved adding following to your project.json file:
"buildOptions": {
    "xmlDoc": true,
    "warningsAsErrors": true,
    "additionalArguments": [ "/ruleset:../../_stylecop/StyleCopeRules.ruleset", "/additionalfile:../../_stylecop/stylecop.json" ]

Additional file is used for settings like company name and default copyright header that should be included into each source code file.

In my test solution I have .NET Core application and class library to show how rules sets are shared between projects. My folders and files structure is displayed in the screenshot below.

StyleCop Analyzers Template Solution

Besides having unified coding style, code analyzers (if rules are activated) can check your code for possible memory leaks and security issues. This can be both – handy and cumbersome if it’s a false alarm. However, it’s always better to double check security related warnings :)

All source code can found on my GitHub:


Update 17/06/2017

It’s recommended to install Visual Studio 2017, and use the latest stable .NET Core version for your .NET Core projects due to breaking changes. Microsoft focuses on the latest versions only. For StyleCop Analyzers set up in VS 2017 see this post.