Auto Format C# Code

Auto Format C# Code

When you're reading code there are a few things which make the process a lot easier, particularly when it was code written by other people.

  1. It's commented well.
  2. It's written in a logical way.
  3. Lines of text aren't really really long meaning you have to side-scroll.
  4. The formatting is consistent.

There's not a lot we can do about the first two other than having a good team, but the second two are something that can be automated and enforced.

In many languages (particularly front-end code) there's a tool named prettier that can configure everything from tab spacing, line length and even if you end a line with a semi-colon or not. I've used it for years and it's brilliant. Unfortunately, it doesn't support C#.

A tool I have found though is CSharpier (https://csharpier.com/), and like Prettier it is an opinionated code formatter.

Add CSharpier to your project

To get started with CSharpier first create a tool-manifest file in the root of your project and then run the install command.

You can do this with the following terminal commands.

1# if you don't yet have a .config/dotnet-tools.json file
2dotnet new tool-manifest
3
4dotnet tool install csharpier

Next add a configuration file to your project so that all team members will produce the same results.

To do this add a JSON file named .csharpierrc.json to the root of the solution.

1{
2 "printWidth": 100,
3 "useTabs": false,
4 "tabWidth": 4,
5 "endOfLine": "auto"
6}

After you add CSharpier you will want to reformat every file in one go, otherwise your going to spend a year going through PRs mostly containing format changes as every file gradually gets reformated.

Do this with the following command.

1dotnet csharpier .

Configure Visual Studio to auto format on save

There's lots of options for triggering the format; You can do it manually, on Pre-commit hooks, or within CI tools, but I find the best is to have a file format on save. This way not only is it making your code readable to everyone else, it also makes it easier to read as your working on it. Plus when tab spacing doesn't fix itself correctly its a good indication there's something wrong with your code.

To do this you will need to install the Visual Studio extension https://marketplace.visualstudio.com/items?itemName=csharpier.CSharpier

Once installed you then need to configure it to format on save. This is located under Tools | Options | CSharpier | General and can either be configured at a global and project level.

CSharpier Visual Studio Config Dialog

And that's it. Now whenever you save a file it will automatically get reformated.