Best Dot NET Code Formatter - DotNet-Format or CSharpier?
** this post is updated on 27-07-2024
In this article:
- Why we need to auto format the code
- DotNet format overview
- How to setup and run DotNet Format
- CSharpier overview
- Pre-commit hook
- Comparison
- Summary
Why we need to auto format the code
Consistently formatted code is crucial for maintainability and readability. Without auto-formatting tools, a codebase can become inconsistent, leading to excessive time spent during code reviews on minor style issues. This focus on formatting can divert attention from more important aspects like functionality and overall design.
As developers, we know that formatting code can be a tedious task. Luckily, tools like dotnet-format and csharpier can automate the formatting of .NET code. These tools offer features such as indenting, line breaks, and code alignment, helping to maintain a consistent style throughout the codebase.
This article will explore two auto-formatting tools in dotnet space: Dotnet-format and CSharpier — and highlight their differences and optimal use cases.
DotNet format overview
dotnet-format is a code formatter for dotnet that applies style preferences to a project or solution. Before .Net 6, we needed to install the standalone DotNet Format tool.
dotnet tool install -g dotnet-format
However, this tool comes with the .NET 6 SDK now, eliminating the need for installation.
EditorConfig
EditorConfig is an open-source file format. It provides a standard way to define coding styles for different file types in a project, such as indentation, line endings, and whitespace. EditorConfig files are stored in the project directory and can be easily shared among team members to enforce consistent code formatting. Many popular code editors and IDEs, including Visual Studio and VS Code, support the EditorConfig format.
dotnet-format will read preferences from a .editorconfig
file. A default set of preferences will be used if the file doesn’t exist.
How to setup and run DotNet Format
To set up dotnet-format, the first step is to add a editorconfig
file. In the root of your dotnet project, you can create this file and add the following content:
1 | // top-most EditorConfig file |
It is worth noting that the rules in the root .editorConfig file will be applied to all projects within the solution. You can also add a .editorConfig file to an individual project, which will only be effective within the project.
Now if you run the following command, the tool will format all the dotnet files in the solution.
dotnet format
There are a number of arguments available with the command
dotnet format whitespace // format the whitespace only
dotnet format --verify-no-changes // dry-run without actually change the file
dotnet format --include [list of files with relative path] // format a list of files
The code style options available for dotnet-format
are more than just spaces/new lines/indentation; you can add Language rules , naming rules , and Formatting rules .
Integrate into Development Workflow
You can integrate the tool into the development flow:
- Manual Formatting: Run dotnet format regularly to ensure code consistency.
- Pre-commit Hooks: Configure Git hooks to automatically format code before committing.
- CI/CD Integration: Include dotnet format as a build step in our CI/CD pipeline to enforce formatting on every commit.
CSharpier overview
CSharpier is an opinionated code formatter for c#. It uses Roslyn to parse your code and re-print it with its rules.
To install CSharpier
dotnet tool install csharpier -g
After installation, we need to configure CSharpier to customize the code style. You can do this by creating a file called .csharpierrc.json
in the project’s root directory. Here is an example :
{ "indent": 2, "useTabs": false, "maxLineLength": 80, "braceStyle": "1tbs", "spacesBeforeConditional": true, "spacesAroundLambdaArrow": "before", "spacesInsideParentheses": false, "spacesInsideSquareBrackets": false }
Now, you can use CSharpier to format your code. To do this, run the following command in the terminal:
dotnet csharpier . // format the contents of a directory and its children
or you can choose to format a particular file or directory
dotnet csharpier /path/to/your/code.cs
CSharpier is remarkably straightforward to set up and use. However, the options with this tool are quite limited. It is intentional in accordance with the Option Philosophy.
it is worth noting that I am impressed with CSharpier’s performance in my testing.
pre-recommit hook
Integration of the auto-formatting tool with a pre-commit hook can ensure that all commits adhere to the predefined rules. We can use Husky
and lint-staged
to achieve that.
Husky is a tool that can define Git hooks as npm scripts in your package.json
file. Git hooks are scripts that run automatically when certain events occur, such as committing or pushing code.
lint-staged
allows you to run linters against files that are staged for commit. This can help to catch issues before they are committed to the repository.
Firstly, let’s install the required tools.
1 | npm install --save-dev husky lint-staged |
Then we can set up Husky.
1 | npx husky-init && npm install |
Running the above command will create a new file .husky/pre-commit
which is the pre-commit hook. Open the file, and replace the last line from npm test
to npm run pre-commit.
Add the following into package.json.
1 | "husky": { |
Now, we have completed the integration of Husky/lint-staged with the auto-formatting tool. In other words, when we try to push a commit, husky
will run the lint-staged
script. If any formatting error is detected, the push will fail.
Comparison
CSharpier and dotnet-format are great tools to format .NET code, but they have some key differences. Here are a few:
- CSharpier is a third-party tool that Microsoft does not officially support, whereas dotnet-format is an official tool included in the .NET 6 SDK above.
- CSharpier is more opinionated than dotnet-format, meaning it has more specific options built-in on how code should be formatted. Depending on your needs, this can be a strength and a weakness.
- dotnet-format is more configurable than Csharpier; it allows you to choose from a wide range of settings to suit your preferences.
- dotnet-format depends on MSBuild to load the .Net projects; it may not be able to work on some of the older versions of projects, i.e., the Xamarin project. CSharpier doesn’t have this limitation.
Both tools can format code for .Net solutions. dotnet-format is more configurable, and CSharpier has limited options. However, CSharpier is faster and doesn’t depend on MSBuild.
Summary
Both dotnet-format and CSharpier are valuable tools for enforcing code style consistency in .NET projects. Each offers distinct advantages and caters to different preferences.
dotnet-format is deeply integrated into the .NET ecosystem and provides a high degree of customization through .editorconfig files. It excels at maintaining consistency within established coding standards.
CSharpier, on the other hand, offers a more opinionated approach with a fixed set of formatting rules. While this might limit customization options, it ensures a uniform style across projects.
Ultimately, the best choice depends on your team’s preferences, the level of customization required, and the overall project requirements. It’s often beneficial to experiment with both tools to determine the best fit for your team’s workflow.
- Title: Best Dot NET Code Formatter - DotNet-Format or CSharpier?
- Author: Sunny Sun
- Created at : 2023-05-05 00:00:00
- Updated at : 2024-07-27 15:02:17
- Link: http://coffeethinkcode.com/2023/05/05/dotnet-format-or-csharpier/
- License: This work is licensed under CC BY-NC-SA 4.0.