- Install the StyleCop Visual Studio Extension
Every developer that will be working on the application with StyleCop should install the Visual StyleCop Extension:
- Add the StyleCop.MSBuild NuGet package to the C# Project
After developers have installed the Visual StyleCop extension StyleCop.MSBuild needs to be added to the C# project for enforcing the rules. StyleCop.MSBuild can be added easily through NuGet:
- Enforce StyleCop warnings as errors
Once the NuGet Package is installed, StyleCop will begin to throw warnings for any code rules that are not passed. Warnings are OK, but we want these to be errors so the solution doesn’t compile. With errors being thrown, developers will have no option but to fix all their styling before they can successfully build.
- Adjust StyleCop settings as needed. Now that the warnings are set to be treated as errors, the solution can no longer build until they are resolved. For example, property headings are required by default in StyleCop. If one is missing, an error will be received like the following:
-Edit the .csproj file in Visual Studio
-In the first <ProjectGroup> section, add:
-Save the file and reload the project
When I add the header, the error is resolved and the build succeeds. Error info also provides the specific StyleCop rule that is being enforced. Rules can be toggled by right-clicking on the project and selecting “StyleCop Settings”
StyleCop provides a slew of different options that can be configured for enforcing. Don’t want to enforce property summaries and file headers? Easily turn them off. Want to make sure everyone is spelling correctly in their summaries and ends their comments with a period? There are options for those as well.
Introducing programming standards like this will likely slow down development as developers begin to familiarize themselves with the new rules and limits. However, it will save a lot of time when transitioning to different teams or back to the client. StyleCop will not fix all issues that occur during a project transition, but it is sure to help with many.