Analyse your code
Create a plan
You MUST conduct code analysis and address the issues you find. Doing this in both your IDE and build & integration pipelines will improve your code, making it easier to maintain, faster, and more secure.
Code analysis can be complex, but this section outlines the steps you SHOULD follow. Create a tailored plan for your team that you regularly review and improve.
Practical tips
Use Redgate SQL Prompt to evaluate T-SQL. See the T-SQL coding standard for help.
Further reading and information
What is Static Analysis? An Explanation for Everyone - NDepend
Enabling High-Quality Code in .NET | Milan Milanović (milanovic.org)
Calculate code metrics to spot problems
Calculate code metrics for each project in your solution and address any that exceed acceptable limits. The table below shows RECOMMENDED levels for each metric.
| Maintainability Index | Cyclomatic Complexity | Depth of Inheritance | Class Coupling | Lines of Executable code | |
|---|---|---|---|---|---|
| 20 - 100 | < 7 | < 5 | < 9 | < 40 |
Calculate code coverage
Calculate test coverage and use the results to identify areas for improvement.
Generate and publish a code coverage report in your pipelines.
Practical tips
Aim to cover a large portion of your code with tests. But prioritise integration tests for areas prone to regressions. This may prove more effective than having unit tests for every method.
Note: Visual Studio's code coverage feature is available only in the Enterprise edition.
Further reading and information
Calculate code metrics - Visual Studio (Windows) | Microsoft Learn
Selective Unit Testing -- Costs and Benefits (stevensanderson.com)
Use code coverage for unit testing - .NET | Microsoft Learn
Code coverage testing - Visual Studio (Windows) | Microsoft Learn
Publish Code Coverage Results task - Azure Pipelines | Microsoft Learn
Exercise - Perform code coverage testing - Training | Microsoft Learn
Check code for style and quality
Ensure your code follows the style (naming, layout, language) and quality conventions described or referenced in this document.
Code Style Options and Analyser Rules
Visual Studio offers a code style options box and Roslyn analyser code style rules. With newer versions of Visual Studio and the .NET SDK, you can run these rules at build time.
Use the dotnet format tool in your build and integration pipelines to check for code style. See later in this section for details.
Use roslyn analysers to ensure .NET code quality
Use Roslyn compiler analysers to check .NET code for style, quality, maintainability and other issues. They are available from Microsoft and third-party providers.
How Roslyn Analysers work:
-
Design-Time Analysis: Analysers run on open files in the IDE, providing immediate feedback.
-
Build-Time Analysis: Can be configured to run during builds to enforce consistent standards.
Use NuGet packages to integrate analysers directly in your code. Avoid relying solely on IDE-specific tools like Visual Studio extensions, ReSharper and SonarQube.
Default Analysers in .NET SDKs
The latest .NET SDKs include many Roslyn analysers pre-installed. The image below shows the analysers available when creating an ASP.NET project targeting .NET 8.0 in Visual Studio.
If using older SDKs, add analysers like Microsoft.CodeAnalysis.NetAnalyzers NuGet package.
Figure 1 Use Roslyn analysers to check your code
{IMAGE PLACEHOLDER}
Third-party Analysers
Include a security analyser, such as SonarAnalyzer.CSharp or SecurityCodeScan.VS2019. For assistance, ask the Software Development Manager or Cyber Security team.
Enabling Rules
Roslyn analysers allow you to configure specific rules. In a .NET 6.0+ project, created with Visual Studio, only a few rules are enabled by default. Enable all relevant rules, disabling only those that produce false positives or are not relevant.
Practical tips
Introducing Code Analysis: Enabling code analysis with all rules on a large codebase can be overwhelming. Start with a few rules and gradually add more until all are enabled.
Important: Code analysis may slow down your development environment. Balance error detection with productivity. Consider running resource-intensive analysis in build or integration pipelines.
Further reading and information
Seven reasons that Roslyn-based Code Analysers are awesome | Tom Wrights Code (tdwright.co.uk)
The .NET Compiler Platform SDK (Roslyn APIs) | Microsoft Learn
Code analysis documentation - Visual Studio (Windows) | Microsoft Learn
Code analysers for .NET Framework | Microsoft Learn
Legacy analysis for managed code - Visual Studio (Windows) | Microsoft Learn
Retrofitting code analysis to legacy projects -- (tdwright.co.uk)
Understanding the impact of Roslyn Analysers on build time - Meziantou's blog
Favourite code analysis tools for .NET Core devs on Azure (zimmergren.net)
Roslyn Team analysers
NuGet Gallery | Microsoft.CodeAnalysis.NetAnalyzers 9.0.0
Roslynator
NuGet Gallery | Roslynator.Analyzers 4 .12.10
xUnit
NuGet Gallery | xunit.analyzers 1.19.0
Style Cop
NuGet Gallery | StyleCop.Analyzers 1.1.118
Security source code analysers
NuGet Gallery | SonarAnalyzer.CSharp 10.5.0. 109200
Static analysers - Training | Microsoft Learn
NuGet Gallery | SecurityCodeScan.VS2019 5.6.7
Source Code Security Analysers | NIST
Source Code Analysis Tools | OWASP Foundation
Code analysis | ReSharper (jetbrains.com) ASP.NET analysers
Code analysis in ASP.NET Core apps | Microsoft Learn
Analysers for ASP.NET Core in .NET 6 (andrewlock.net)
ReSharper
Configure code analysis rules
Follow these steps when configuring code analysis:
| CONFIGURATION STEP | Details |
|---|---|
| ADD AN .editorconfig FILE | Place in the root of your solution and commit to source control to ensure consistent settings across the team. |
| SET-UP INITIAL RULES | Generate settings using Visual Studio's code style options or a template (see further reading). Adjust rules to align with team or organisational conventions. |
| DEFINE RULE SEVERITY | Set critical rules to error to ensure violations fail the build. Configure the Directory.build.props or .csproj files (SDK-style projects) to enable style and quality checks during builds. |
| ENFORCE CODE STYLE | Enforce code style checks during builds where your .NET version supports it. |
| APPLY GOOD PRACTICE | Treat warnings as errors to promote higher code quality. |
Practical tips
Be mindful of the challenges with .editorconfig, including known Visual Studio UI limitations. Read this blog before you start! --
C# code style by EditorConfig in .NET 5 SDK and beyond | Mews Developers
You MAY develop team-specific styles if the provided conventions don't meet your needs.
.editorconfig
How to enforce a consistent coding style in your projects - Meziantou's blog
Code style options and code cleanup - Visual Studio (Windows) | Microsoft Learn
Enforce code style rules - Visual Studio (Windows) | Microsoft Learn
.NET code style rule options - .NET | Microsoft Learn
C# editor formatting options - Visual Studio (Windows) | Microsoft Learn
.editorconfig templates
EditorConfig settings - Visual Studio (Windows) | Microsoft Learn
project-system/.editorconfig at main · dotnet/project-system · GitHub
.csproj config
Code Analysis: MSBuild properties for Microsoft.NET.Sdk - .NET | Microsoft Learn
Enable NET Analyzers: MSBuild properties for Microsoft.NET.Sdk - .NET | Microsoft Learn
Run code analysis in your pipelines as well as the IDE
Run code analysis during builds catch issues early, using tools like MSBuild & dotnet format.
Further reading and information
Enforce .NET code style in CI with dotnet format - Meziantou's blog
Check third-party packages
Check for vulnerabilities and licence issues in third-party dependencies by integrating tools like GitHub Advanced Security for Azure DevOps.
Further reading and information
Publish and review metrics
Track code health by publishing metrics from analysis tasks to server dashboards.
Regularly review these metrics and address problem areas to maintain quality.
Further reading and information
Generate code metrics from the IDE or command line - Visual Studio (Windows) | Microsoft Learn
Publish Code Coverage Results task - Azure Pipelines | Microsoft Learn
Exercise - Perform code coverage testing - Training | Microsoft Learn
Recap
Recap: Analyse your code
-
Create a plan.
-
Calculate code metrics.
-
Calculate code coverage.
-
Check for code style and quality.
-
Use Roslyn analysers.
-
Configure code analysis rules.
-
Run code analysis in your build pipelines.
-
Check third party packages.
-
Publish metrics.