Auto Format your Code on save with Visual Studio

Auto Format your Code on save with Visual Studio

Code formatting is a very important element when developers work together on a project - and you are always well advised not to invent your own formatting rules, but to use those that are a standard or de facto standard in the respective programming language.
In C#, many rules are now controlled via the editorconfig, but there is still a lack of standardized formatting tools in .NET - dotnet format simply does not support many things - so that different functionalities exist in different IDEs (Visual Studio, Visual Studio Code, Rider).

Visual Studio

In Visual Studio, formatting options are not applied automatically by default, but you have to use cleanup profiles to define which rules are to be applied.

These can be accessed via Analyze -> Code Cleanup -> Configure:

2024-11_VisualStudio2022-CodeCleanupConfigure

In my case, I have activated the following options that are important for me and for us:

OptionDescription
Add accessibility modifiersAdds missing modifiers such as public or private
Order modifiersSorts the modifiers in the correct order
Remove unnecessary castsRemoves unnecessary casts that make the code more cumbersome to read
Format documentFormats the document correctly using tabs, whitespaces and the corresponding brackets
Remove unnecessary imports and usingsRemoves usings that are no longer needed, e.g. due to refactoring
Sort Imports and usingsSorts all usings
Apply file header preferencesAdds or updates file headers if they are optionally stored in the editorconfig
Apply var preferencesIn my case, replaces all var definitions with the correct type
Apply readonly struct preferencesAdds a readonly to all corresponding structs where it makes sense and is necessary (almost always)
Apply new() preferencesTurns a Class c = new Class() into a Class c = new();

All options mentioned here are my settings. The Code Cleanup uses the Visual Studio Config and the editorconfig.

Activate Code Cleanup on Save

The automatic Code Cleanup is executed every time you save (CTRL+S), which costs a little performance if many open files are saved at the same time. However, if you have a sufficiently powerful computer, you should definitely activate this - it saves a lot of work.

This can be activated in the Visual Studio options under Text Editor -> Code Cleanup and then check the box and select the profile.

2024-11_VisualStudio2022-CodeCleanupSave

The code is formatted each time it is saved - which makes life much easier.