29
Enforcing a consistent code quality and style in your team-wide .NET projects
Each developer has his/her own style of coding, usually inherited from personal preferences, habits and years of experience. Just think of naming conventions, indentation, spaces, curly braces, blank lines, etc.: there are many elements that can be typed in various ways, and none of them are wrong but just different.
Especially in big teams, mixing different styles has some consequences:
Then, the goal is creating a team style rather than a personal style. Moreover, keeping the solution free of warnings is definitely a good move.
Just few years ago, Microsoft (finally) added the
.editorconfig
support to Visual Studio. This file defines a set rules that override the local Visual Studio settings. So you can work on multiple projects owned by different teams with their own rules without having to change every time your local Visual Studio settings.And above all, the whole team has the same settings.
Last but not least, it is possible to define rules about code quality as well. To give you an idea, it is possible to throw a compiler error if an
IDisposable
object is not properly disposed, or when an async
method is not await
ed.NOTE: Visual Studio Code needs this extension to work with
.editorconfig
files.
Visual Studio displays an UI when you try to open the
.editorconfig
file, but personally I don't like it. I think it is way quicker to manually edit it - usually I use VS Code.So, open the file and set it as the top most
.editorconfig
file by setting:root = true
Then, you can set any rule you would like to set. Personally, I start with the indentation rules for any file in the solution, and then I go deeper with more specific rules for each language and namespace. For example:
[*] # Any file uses space rather than tabs
indent_style = space
# Code files
[*.{cs,csx,vb,vbx}] # these files use 4 spaces to indent the code
indent_size = 4
insert_final_newline = true
charset = utf-8-bom
# XML project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# XML config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Powershell files
[*.ps1]
indent_size = 2
# Shell script files
[*.sh]
end_of_line = lf
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
You can set hundreds of rules, of any type. On Microsoft Docs there is an (almost) complete list of available rules that you can try locally and find the balance that suits best for your needs.
Each rule can have a specific severity: you can treat a warnings as errors or demote them to suggestions, or even disable them. Be careful, the most bottom rule has the precedence over the rest.
Each rule can have a specific severity: you can treat a warnings as errors or demote them to suggestions, or even disable them. Be careful, the most bottom rule has the precedence over the rest.
NOTE: By default, Visual Studio only analyses open documents. If you wish to scan the entire solution go in
Tools
-> Options
-> Text Editor
-> C#
(or your favorite language) -> Advanced
-> Set Background Analysis Scope
to Entire Solution
This doesn't affect MsBuild
, that instead needs to enable analysers in your csproj
s by checking EnableNETAnalyzers
and EnforceCodeStyleInBuild
!<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<EnableNETAnalyzers>True</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
</PropertyGroup>
Sometimes you want to define some rule (or exception) for a specific project or namespace. For example, I want to enforce the suffix
Luckily
Async
to any asynchronous method in the solution but for unit tests and controllers.Luckily
.editorconfig
files allow you to achieve a solution quite straightforward. Basically, you have two ways:.editorconfig
fileAt the bottom of the
.editorconfig
, define the namespace of where you would like to apply the exception. For example:[src/**{.UnitTests,/Controllers}/**.cs]
# Async methods should have "Async" suffix
dotnet_naming_rule.async_methods_end_in_async.severity = none
Inheritance is a good alternative. Do you remember the
root
property we set at the beginning? That means that the given .editorconfig
is applied to the whole solution. But however it is possible to create other .editorconfig
files in subfolders that will inherit all the rules from the root
file. Rules defined here takes the precedence. Getting back the previous example, you can navigate to the Controllers
/UnitTests
folders and create a new file. Do NOT define the root=true
property and add this:# Async methods should have "Async" suffix
dotnet_naming_rule.async_methods_end_in_async.severity = none
This is a tricky question with several solutions.
The first solution is to use the built-in Visual Studio feature -
Code clean up
. Personally I don't like it for the following reasons:For these reasons, I had been using
Productivity Power Tools
, an (historical) extensions developed by Microsoft. It provides a feature to format the entire file when the file is saved (through UI or the shortcut CTRL+S). It makes simply impossible to forget to format your file before committing it in your source control.But, unfortunately Microsoft decided to remove this feature from the PPT 2022 version - apparently without any reason, there are plenty of negative feedbacks for this.
Luckily, a developer named
Elders
has published an extension called Format document on Save and it does simply what its name says: it formats the document when the user save it!Nope! This extension is able to read a file named
.formatconfig
that you can check in your source control and share with your team. It doesn't need to be added to the Visual Studio solution, but just to stay in the same level of the solution file. Local user preferences are ignored.Here's an example of definition:
root = true
[*.*]
enable = true
enable_in_debug = true
command = Edit.FormatDocument Edit.RemoveAndSort
allowed_extensions = .*
denied_extensions =
Anything familiar? π±βπ»
Last thing to do is leaving you a link to a repository where you can find a fully working solution and especially an
.editorconfig
file with lot of rules defined. You can get the remaining ones on Microsoft Docs.Enjoy! π
29