.NET Code Analysis (CA)
.NET Code Analysis is a static analysis feature that detects code quality, style, performance, and security issues to fix them in the early stages of development. In modern .NET development, "Roslyn Analyzers" based on the Roslyn compiler platform are used as the standard.
What is Code Analysis (CA)?
Code Analysis inspects source code at compile time and reports potential bugs and coding standard violations.
Key Features
- Real-time Feedback: Warnings and errors are displayed in IDEs like Visual Studio or VS Code while writing code.
- Build-time Verification: You can enforce code quality on the CI/CD pipeline.
- Customizable: You can finely configure rule enable/disable status and severity.
Difference from Legacy FxCop
Historically, a static analysis tool called "FxCop" was used, but it has now been integrated into Roslyn Analyzers (.NET Analyzer). While FxCop analyzed compiled assemblies, Roslyn Analyzers analyze source code, enabling richer and faster feedback.
Types of Rules
The .NET SDK includes numerous analysis rules. These are mainly classified into the following categories:
1. Code Quality Rules (CAxxxx)
Detects issues related to API design, security, performance, reliability, etc.
- Design: Adherence to library design guidelines (e.g., how interface implementation should be done).
- Performance: Detecting code that negatively affects performance (e.g., unnecessary string concatenation).
- Security: Detecting vulnerable code that could become security holes.
- Reliability: Detecting code that might make the application behavior unstable.
- Usage: Rules related to the correct usage of the Framework.
2. Code Style Rules (IDExxxx)
Rules related to code readability and formatting consistency.
- Usage policy of
var - Whether curly braces
{}can be omitted - Namespace declaration style (e.g., File-scoped namespace)
3. Third-party Analyzers
Additional analyzers can be installed as NuGet packages.
- StyleCop.Analyzers: For applying strict style guidelines.
- SonarAnalyzer.CSharp: Detailed analysis compliant with SonarQube.
- xUnit.Analyzers: Best practice checks specific to test code.
Configuration and Setup
The behavior of .NET code analysis is mainly controlled by the project file (.csproj) and the .editorconfig file.
Settings in Project File
Configure the analysis level for the entire project.
<PropertyGroup>
<!-- Treat all warnings as errors (Recommended) -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Enable .NET code analysis features (Default is true since .NET 5) -->
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<!-- Specify analysis level (latest uses the latest SDK recommended settings) -->
<AnalysisLevel>latest</AnalysisLevel>
<!-- Whether to enable all recommended settings -->
<AnalysisMode>All</AnalysisMode>
</PropertyGroup>
Detailed Configuration via .editorconfig
Using .editorconfig, you can set the Severity for each individual rule. Placing it at the repository root applies it to all projects.
Severity Levels
- error: Fails the build. Immediate fix required.
- warning: Build succeeds but shows a warning (Build fails if
TreatWarningsAsErrorsis enabled). - suggestion: Shows a hint like "..." in the IDE. Does not remain in the build log.
- silent: No highlighting in the editor, but available as a fix suggestion (lightbulb icon).
- none: Disables the rule.
Configuration Example
# .editorconfig
# Settings per file
[*.cs]
#### Core Analysis Rules ####
# CA1062: Validate null checks for public method arguments
dotnet_diagnostic.CA1062.severity = error
# CA1822: Point out members that can be marked as static
dotnet_diagnostic.CA1822.severity = warning
# CA2007: Check whether to use ConfigureAwait (Disable as it's unnecessary in ASP.NET Core)
dotnet_diagnostic.CA2007.severity = none
#### Style Rules ####
# Enforce usage of var (csharp_style_var_for_built_in_types)
csharp_style_var_for_built_in_types = true:suggestion
# Recommend File-scoped namespace usage
csharp_style_namespace_declarations = file_scoped:warning
Best Practices
1. Aim for Validated Zero Warnings (TreatWarningsAsErrors)
For production-quality code, it is recommended to set <TreatWarningsAsErrors>true</TreatWarningsAsErrors> to treat warnings as errors. Ignoring warnings can lead to a "Broken Windows Theory" state where critical issues are missed.
2. Manage .editorconfig Hierarchically
- Root Directory: Strict rules common to the entire project.
- Test Projects: Override with settings that relax some rules (like naming conventions or documentation requirements).
3. Regularly Update AnalysisLevel
New rules are added with .NET SDK updates. Setting <AnalysisLevel>latest</AnalysisLevel> automatically applies new rules, but there is a risk of breaking the build upon SDK updates. If stability is a priority, fix the version like <AnalysisLevel>8.0</AnalysisLevel> and upgrade systematically.
4. Team Consensus
Enabling all rules might slow down development speed. Ideally, set rules that are considered "noise" by the team to none without hesitation, and only set rules that truly need to be followed to error or warning.
Conclusion
Implementing appropriate code analysis is a powerful way to reduce the burden of code reviews and automatically ensure quality. Leverage .NET standard features and .editorconfig to build an analysis environment that suits your team.