DEV Community

Cover image for StyleCop: Create code with style
Fernando Sonego
Fernando Sonego

Posted on

StyleCop: Create code with style

One of the discussions in the teams of programmers always styles that you must code. Most of the time, no two programmers write code in the same way as the other. This is because it is more a matter of taste than of a methodology itself.

Let's imagine that the team agrees and we have a person who is dedicated to reviewing the coding style, quite tedious, right? This is where we can use an automation tool like StyleCop.

What is StyleCop?

What is StyleCop?
StyleCop parses our C # code to apply a set of style and consistency rules to our code. We must bear in mind that there are 2 versions of StyleCop. Until recently, StyleCop was used, but now the recommendation is to use StyleCop Analyzer because the previous version will not have major changes or new features.

Let's see an example of things that we can solve with StyleCop.

if(condition) return;

The tool will be in charge of identifying all the places where the declaration of the first part of the example is found and it alerts us when compiling that there is code that does not comply with the style rules.

Recall that these rules must be agreed with the team. By default, StyleCop, brings many rules, for example, quantity of white spaces, how to declare names of properties, variables, or methods, but perhaps, we do not like all of them or suit our team.

Configure StyleCop

After creating our project to add StyleCop we must do it from a Nuget package. For this we will right-click on our project, select "Nuget Package Manager" and the sale will open. In the search engine, we will write StyleCop.Analyzers and press install. You can see it in the following animation.

StyleCop

Perfect! We already have it available in our project.

How to use StyleCop?

The first thing we will do is modify our main method with the following code:

using System;

namespace StyleCopDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloWorld1();
            HelloWorld2();
            HelloWorld3();

            Console.ReadLine();
        }

        private static void HelloWorld1()
        {
            Console.WriteLine("Hello World! 1");
        }

        private static void HelloWorld2()
        {
            Console.WriteLine("Hello World! 2");
        }
        private static void HelloWorld3()
        {
            Console.WriteLine("Hello World! 3");
        }
    }
}

We will see that in our error list window, errors that begin with the StyleCop Analyzer SA code will appear in the Warnings section.

StyleCop

A little trick, if we click on the code, it will take us to the website that will explain what this error is due to and the information corresponding to the rule that triggers it and how we must repair that code to eliminate the warning.

StyleCop

Configure Rules

To configure the rules that will be applied to the code we have 2 paths. The first is to do it from the rules panel, it is accessed by right-clicking on the project and selecting properties. The second is to add a stylecop.json file to the project.

To see the first panel of rules we must go to Solution Explorer, display dependencies, analyzers, finally, we select StyleCope.Analyzer.

StyleCop

We can configure what level of severity it has between error, warning, suggestion, silence, or none.

StyleCop

Each of the options has a different result, the most important:

  • Warning, appears in the list of errors in the warnings section. *Error, it will be shown in the error section, and the invalid code is highlighted in red in the editor preventing the compilation of the project. *Security, it will appear in the suggestions section. *None, the rule will not be checked.

Another way to configure the rules is to use a stylecop.json file. We can create it automatically from a rule. When the lamp is marking us, press and select "Add StyleCop setting ...". This will create the file with the rule.

StyleCop

The rule we created has to do with copyright as the head of the files. In our JSON file, in “companyName” we complete with “StyleCop DEMO”. The next step is to add the file as an additional parser file. For this, we have to go to the properties of the file and configure it in configuration actions. A ready bird when applying the rule we will see how it puts the new companyName.

StyleCop

Now we can see that the using is marking us. One of the rules says that all using must be declared inside the namespaces:

StyleCop

If we want to change this line, and leave the using ones outside the namespace, we can add the rule in our configuration file.

'orderingRules': {
     'usingDirectivesPlacement': 'outsideNamespace'
 }

To see all the rules we can consult the corresponding documentation. But almost always the default rules cover all basic and standard needs.

Finally, let's see one more example:

public class Customers {
     public string _name;
}

We have a class that does not respect several rules. First, we have the rule "a C# code file contains more than one unique type." executing the rule will move the type to a new c # file. Second, we have the class format rule. Third and last, it does not say that the class must be documented but suppose that we do not want to do so, we can add an exception so that it is not taken into account.

StyleCop

Conclusions

We must always reach an agreement with the team that regulations we want to implement and how serious they can be not respecting them. For this reason, the best way is to let StyleCop do the work for us with only an initial setup effort. This guide is quite simple, but I invite you to continue investigating a little more about this excellent tool.

Top comments (0)