How to enforce a consistent coding style in your projects

 
 
  • Gérald Barré

This post is part of the series 'Coding style'. Be sure to check out the rest of the blog posts of the series!

Every company or team has its own coding style. Coding style covers naming conventions, spacing preferences, and language feature usage. Do you use tabs or spaces, and how many? Do you use PascalCase or camelCase? Do you prefix field names with _? Do you always use var or only when the type is explicit? These are just a few of the questions that define a team's style.

In an open or inner-source project, you want to ensure every contributor follows your coding style so your codebase stays consistent. It also reduces the number of review comments about minor formatting issues.

Let's look at which tools are available to help enforce your coding style!

#.editorconfig file

Here's the introduction from editorconfig.org:

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs. The EditorConfig project consists of a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and adhere to defined styles. EditorConfig files are easily readable and they work nicely with version control systems.

EditorConfig is supported natively by Visual Studio and by Visual Studio Code via a plugin (download). Many other IDEs support it natively or via a plugin, including JetBrains Rider.

##How does it work?

The IDE looks for a file named .editorconfig at the root of your repository. This file contains instructions for different files based on a glob pattern. You have global instructions like indent_style or indent_size, and C#-specific instructions like dotnet_sort_system_directives_first.

The .editorconfig file lives in the repository, so every contributor can use it to write code that matches the team's coding style. Visual Studio will also show quick fixes to bring your code in line with the style defined in the configuration file.

Here's an example:

INI
[*]
indent_style = space

[*.{cs,csx,vb,vbx}]]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom

[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2

[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2

[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
dotnet_style_require_accessibility_modifiers = always:warning

# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = false:warning
dotnet_style_qualification_for_method = false:warning
dotnet_style_qualification_for_event = false:warning

# ...

Here are some useful resources about editor config for .NET:

Build errors in Visual StudioBuild errors in Visual Studio

Quick Fixes using the quick action menuQuick Fixes using the quick action menu

You can format your existing code to follow the rules set in the .editorconfig file using the global tool dotnet-format:

Shell
dotnet tool install -g dotnet-format

Then, you can use dotnet format in a folder that contains your solution

Shell
cd c:\sources\my-project
dotnet format

Diff before and after running dotnet formatDiff before and after running dotnet format

#Linters / Roslyn Analyzers

Another useful tool for enforcing a consistent coding style is a linter. A linter runs on your codebase and flags violations of defined rules. Linters often include best-practice rules in addition to formatting rules. For instance, they can detect incorrect API usage – if you work with async/await, a linter can catch missing awaits. In C# you can use StyleCop. For TypeScript, there is tslint. There are linters for almost every language.

Here's an error detected by tslint:

tslint outputtslint output

You can check my other post about tslint for more information.

Roslyn analyzers work like a linter but are fully integrated into the build pipeline and the IDE, and may include refactoring actions to fix issues automatically. Many analyzers are available. Check the store to find useful analyzers. I also have a nice list of Visual Studio extensions in this post.

Roslyn analyzerRoslyn analyzer

#Visual Studio Code configuration

Visual Studio Code has a settings file that contains lots of options to format documents. It can contain settings for all languages and also per language. Create a file .vscode\settings.json, and set the values you want to share with your team.

JSON
{
  // Global settings
  "files.insertFinalNewline": false,
  "files.trimFinalNewlines": false,
  "files.trimTrailingWhitespace": false,

  // Per language settings
  "javascript.format.enable": true,
  "javascript.format.insertSpaceAfterCommaDelimiter": true,
  "javascript.format.insertSpaceAfterConstructor": false,
  "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true,
  "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": true,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": false,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false,

  "[git-commit]":  {
    "editor.rulers": [72]
  },

  // ...
}

The full list of settings is available in the documentation: Visual Studio Code - Default Settings

#Resharper / Rider

I don't use Resharper or Rider (the JetBrains .NET IDE), but many developers do. ReSharper includes a rich set of formatting options that can be saved to a file in your repository. Everyone using ReSharper with your repository will then pick up those shared settings – it works like a .editorconfig but for ReSharper. ReSharper also reads some settings from .editorconfig, so having both is useful when not every contributor uses ReSharper.

Resharper code formatting optionsResharper code formatting options

You can use Resharper CLI (free) to clean up your code. It's a command-line tool that reads the configuration files and reformats all documents in your solution.

Here's some information from the documentation of Resharper:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?