paint-brush
StyleCop for .NET Makes Code Betterby@igorlopushko
10,845 reads
10,845 reads

StyleCop for .NET Makes Code Better

by Igor LopushkoJanuary 7th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

StyleCop analyzes C source code to enforce a set of style and consistency rules. The rules for writing code improve software readability by allowing developers to understand new code faster and better. The NuGet package is the most convenient method to use StyleCop since it does not require any additional configuration of the IDE. Most likely your team would like to have custom rules set to match code styles and conventions defined in your team or organization. There is a complete specification of the ruleset for your project.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - StyleCop for .NET Makes Code Better
Igor Lopushko HackerNoon profile picture


Do you have any coding standards for your projects? Microsoft defines C# coding conventions, and it could be a starting point to follow. There are many reasons why it is important to apply coding standards for your project:


  • The same rules for writing code improve software readability by allowing developers to understand new code faster and better.
  • The codebase is almost never fully supported by its original author. Most of the total cost of software is spent on its maintenance.
  • Helps to demonstrate best practices.
  • Like any other product, the software must be "well packaged" and clean.


StyleCop de facto is a standard tool for .NET. It analyzes C# source code to enforce a set of style and consistency rules. Default rules set could be used, or you can configure your own. The cool thing is that warnings and errors are shown in the IDE during the compilation.


It was introduced in 2008 and is now available in two options: the StyleCop Visual Studio extension and StyleCop NuGet package. The NuGet package is the most convenient method to use StyleCop since it does not require any additional configuration of the IDE. That is great when working in a team. Also, if you use other IDEs than Visual Studio (e.g., JetBrains Rider on Mac), it will perfectly do the job. So let’s dive in.

StyleCop Installation

As described above NuGet package is the best way to use StyleCop. To add the StyleCop NuGet package to your project, you should run the following command:


Install-Package StyleCop.Analyzers


The NuGet package manager also could be used to find and install the StyleCop NuGet package directly in the IDE.


After the installation, you can compile your project and see if there are any errors or warnings in the output bar. For the simple Hello World console application, you could see something like this:


Build started 01/03/2022 23:33:44.
       "/ConsoleApp1/ConsoleApp1.csproj" (build target) (1) ->
       (CoreCompile target) -> 
         /ConsoleApp1/Program.cs(1,1): warning SA1633: The file header is missing or not located at the top of the file.
         /ConsoleApp1/Program.cs(5,11): warning SA1400: Element 'Program' should declare an access modifier
         /ConsoleApp1/Program.cs(1,1): warning SA1200: Using directive should appear within a namespace declaration
         /ConsoleApp1/Program.cs(6,6): warning SA1028: Code should not contain trailing whitespace
         CSC : warning SA0001: XML comment analysis is disabled due to project configuration

    5 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.35


When the StyleCop NuGet package is installed, the default rules set is applied. Most likely, your team would like to have custom rules set to match code styles and conventions defined in your team or organization.

Custom Ruleset

As you have noticed, a *.ruleset file is an XML file that could provide the following features:


  • Enable and disable individual rules
  • Configure the severity of violations reported by individual rules


I recommend downloading the default ruleset and modifying it according to your needs. There is a complete specification of the rules here.


To plug in a custom ruleset to your project you should add *.ruleset file to your project and modify the csproj file by adding CodeAnalysisRuleSet tag as follows:


<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        ...
        <CodeAnalysisRuleSet>settings.ruleset</CodeAnalysisRuleSet>
    </PropertyGroup>
    ...
</Project>

Configuring StyleCop

Another way to configure StyleCop is to add stylecop.json file to the project. It gives the following opportunities:


  • Specify project-specific text, such as the name of the company and the structure to use for copyright headers
  • Fine-tune the behavior of certain rules


For example, to set the value of the number of columns to use for each indentation of code to 4 and use spaces to indent, do the following:


{
  "settings": {
    "indentation": {
      "indentationSize": "4",
      "useTabs": "false"
    }
  }
}


For more details, use configuration specification here.

Summary

StyleCop analyzes C# source code to enforce a set of style and consistency rules. Use it as a NuGet package which is the best way to work in a team. Use custom *.ruleset and stylecop.json files to tune the StyleCop according to your project needs.