Search code examples
c#visual-studioeditorconfig

How to format C# code in an automated way?


I'd like to apply all formatting VS can apply to C# files (anything listed under Tools->Options->Text Editor->C#->Code Style, stored in a .editorconfig file on the project level), and verify whether it has been applied, but this should be initiated from the commandline and run on pretty much all files in a project, such that it can also run on CI builds for instance. I.e. maintain consistent code style across a large codebase, and enforced by CI so that lack of formatting leads to build warnings/errors; seems like a rather common requirement, there are tools for most common languages, but I couldn't find much specific to.Net ones?

I'm asking about VS, but if there's another tool which can apply similar formatting that would be fine as well; on that note: clang-format would be the ideal option were it not that it doesn't supply the same level of options VS has. Only option I see currently is creating something custom using EnvDTE to either manually go over all documents and call Edit.FormatDocument on them or perhaps to run 'Code Cleanup' on the solution. And then verifying whether everything has been formatted would entail applying the formatting and then checking if any files were changed.


Solution

  • You can use the dotnet-format tool to format your source code. It will format based on the presence of a .editorconfig (or apply some defaults if there is none). You can find all the info for that tool here.