Introduction
Consistent code formatting is essential for maintainable ASP.NET Core applications, especially in team environments. Microsoft provides powerful tools to automate code formatting in .NET projects: dotnet-format and EditorConfig. This guide covers how to set up and use these tools effectively to ensure your C# code is consistently formatted across your entire project.
dotnet-format Overview
dotnet-format is a code formatter for .NET that applies style preferences to a project or solution. It's powered by the Roslyn .NET compiler platform and supports:
- Formatting C# and Visual Basic code
- Enforcing code style rules
- Fixing analyzer violations
- Organizing using directives
- Removing unnecessary imports
Installation
There are two ways to install dotnet-format:
As a Global Tool (Recommended)
dotnet tool install -g dotnet-format
As a Local Tool
For project-specific usage, you can install it as a local tool:
# Create tool manifest if you don't have one
dotnet new tool-manifest
# Install dotnet-format locally
dotnet tool install dotnet-format
Verify installation:
dotnet format --version
EditorConfig Setup
EditorConfig files define the formatting rules that dotnet-format applies. Create a .editorconfig file in your project root:
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Default settings:
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
# C# files
[*.cs]
# New line preferences
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_switch_labels = true
csharp_indent_labels = one_less_than_current
# Space preferences
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_after_comma = true
csharp_space_after_dot = false
# Naming styles
dotnet_naming_style.pascal_case_style.capitalization = pascal_case
# Use PascalCase for constant fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const
# Whitespace
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true:silent
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
# Analyzers
dotnet_code_quality.ca1802.api_surface = private, internal
# C# code style settings:
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
For more advanced configurations, you can create role-specific EditorConfig files. For instance, you might have stricter rules for library code than for test code.
Command Line Usage
Basic commands for using dotnet-format:
# Format the current directory
dotnet format
# Format a specific project or solution
dotnet format YourProject.csproj
dotnet format YourSolution.sln
# Verify formatting without making changes
dotnet format --verify-no-changes
# Format only specific files
dotnet format --include Program.cs Controllers/*.cs
# Check for formatting issues without making changes
dotnet format --check
Advanced Usage
# Format and fix code style issues
dotnet format style
# Format and organize imports
dotnet format whitespace
# Format and remove unnecessary imports
dotnet format analyzers
# Run all of the above
dotnet format --severity info
CI Integration
Integrating dotnet-format into CI pipelines ensures all code meets formatting standards before being merged.
GitHub Actions Example
name: Code Format Check
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
format-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
- name: Install dotnet-format
run: dotnet tool install -g dotnet-format
- name: Check format
run: dotnet format --verify-no-changes --verbosity diagnostic
# Optional: automatically fix formatting issues
# - name: Fix formatting
# if: \${{ failure() }}
# run: dotnet format
Azure DevOps Example
- task: DotNetCoreCLI@2
displayName: Install dotnet-format
inputs:
command: 'custom'
custom: 'tool'
arguments: 'install -g dotnet-format'
- task: DotNetCoreCLI@2
displayName: Run dotnet-format
inputs:
command: 'custom'
custom: 'format'
arguments: '--verify-no-changes --verbosity diagnostic'
IDE Integration
Modern .NET IDEs support EditorConfig and can apply formatting rules automatically:
Visual Studio
- EditorConfig support is built-in for Visual Studio 2019+
- Enable "Format document on save" in Tools → Options → Text Editor → C# → Advanced
- Configure Code Cleanup profiles (Edit → Advanced → Configure Code Cleanup)
Visual Studio Code
- Install the C# extension by Microsoft
- Install EditorConfig for VS Code extension
- Configure Format On Save in Settings
// settings.json
{
"editor.formatOnSave": true,
"omnisharp.enableRoslynAnalyzers": true,
"omnisharp.enableEditorConfigSupport": true
}
JetBrains Rider
- EditorConfig support is built-in
- Enable "Format on save" in Settings → Editor → General → Formatter
- In Settings → Editor → Code Style → C#, you can export settings to EditorConfig
Best Practices
Follow these best practices for effective code formatting in ASP.NET Core projects:
- Store the .editorconfig file in version control to share rules with your team
- Layer .editorconfig files for different parts of your project if needed
- Start with Microsoft's recommended settings and customize as necessary
- Run formatting checks as part of Pull Request validation
- Set up pre-commit hooks to format code automatically
- Gradually introduce formatting rules to avoid large disruptive changes
For git pre-commit hooks, you can use tools like Husky.NET:
dotnet tool install husky --global
cd YourProject
dotnet husky install
dotnet husky add pre-commit -c "dotnet format"
Conclusion
dotnet-format and EditorConfig provide a powerful toolset for ensuring consistent code formatting in ASP.NET Core projects. By automating formatting, you reduce the mental overhead for developers and eliminate formatting-related discussions in code reviews.
With proper CI integration and IDE setup, you can ensure that all code in your project follows the same style guidelines, making your codebase more readable, maintainable, and professional. These tools are an essential part of modern .NET development practices that help teams deliver higher quality code more efficiently.