Zum Inhalt springen

Static code analysis for .NET: three layers compared

A pull request with five defects runs through the SDK analyzers, SonarAnalyzer, and CodeCharter. The runs show which layer reports what and where they overlap.

by CodeCharter
  • dotnet
  • code-quality
  • architecture

A tech lead is responsible for a .NET solution whose build runs with -warnaserror and uses the .NET SDK analyzers in their default configuration. A pull request has passed with a green build although it contains five typical defects. She has to decide which analysis to add to the pipeline. The solution and the pull request are constructed for this article; all output comes from real runs with .NET SDK v10.0.402, SonarAnalyzer.CSharp v10.36.0.15337, and CodeCharter v1.7.0.

The pull request pr/order-report changes a project Shop with the namespaces Shop.Domain, Shop.Infrastructure, Shop.Notifications, and Shop.Reporting:

  1. SqlOrderRepository.FindOrDefault catches every exception with catch (Exception) { } and discards it.
  2. MailNotifier.NotifyCancelled is declared as async void.
  3. OrderService in Shop.Domain holds and injects SqlOrderRepository from Shop.Infrastructure; on main it used the contract IOrderRepository.
  4. The new class OrderReport has 34 public methods on 1,522 lines.
  5. OrderService.cs starts with an unnecessary using System.Text;.
$ dotnet build Shop.slnx -warnaserror
  Determining projects to restore...
  All projects are up-to-date for restore.
  Shop -> ...\src\Shop\bin\Debug\net10.0\Shop.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)
…

SDK analyzers in the build

For projects targeting .NET 5 or later, the SDK's code quality rules (CA) run without a package. According to Microsoft's code analysis documentation (as of November 5, 2025), .NET 10 reports 29 rules as warnings or errors in the default configuration. They come from the categories Interoperability, Performance, Reliability, and Usage. None of them checks empty catch blocks, async void, layers, or class size, which is why the build above stays green.

The AnalysisLevel property enables more rules. With latest-recommended, the build reports only CA1822 twice and ends with exit code 1. With latest-all, it reports three errors:

$ dotnet build Shop.slnx -warnaserror -p:AnalysisLevel=latest-all
  Determining projects to restore...
  All projects are up-to-date for restore.
...\src\Shop\Infrastructure\SqlOrderRepository.cs(32,9): error CA1031: Modify 'FindOrDefault' to catch a more specific allowed exception type, or rethrow the exception (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1031) [...\src\Shop\Shop.csproj]
...\src\Shop\Notifications\MailNotifier.cs(20,23): error CA1822: Member 'NotifyCancelled' does not access instance data and can be marked as static (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822) [...\src\Shop\Shop.csproj]
...\src\Shop\Notifications\MailNotifier.cs(12,23): error CA1822: Member 'NotifyShippedAsync' does not access instance data and can be marked as static (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822) [...\src\Shop\Shop.csproj]
  Shop -> ...\src\Shop\bin\Debug\net10.0\Shop.dll

Build FAILED.
…

CA1031 reports the catch because it catches System.Exception. According to the "Cause" section of the CA1031 page, the rule applies only to general exception types, so an empty catch (KeyNotFoundException) would not be covered. That variant did not run in the case. CA1822 suggests static and also hits NotifyShippedAsync, which already exists on main. The build of main therefore fails with latest-all as well. Size and coupling stay unreported here too. According to the MSBuild reference (as of September 21, 2026), even latest-all does not enable the code metrics rules CA1501, CA1502, CA1505, CA1506, and CA1509. They can be enabled one by one with dotnet_diagnostic.CAxxxx.severity; the case did not check that.

Code style rules (IDE) do not run in a command-line build by default. The build reports the unnecessary using only when three settings come together: EnforceCodeStyleInBuild=true, the line dotnet_diagnostic.IDE0005.severity = warning in .editorconfig, and XML documentation in the project.

$ dotnet build Shop.slnx -warnaserror -p:EnforceCodeStyleInBuild=true -p:GenerateDocumentationFile=true
  Determining projects to restore...
  All projects are up-to-date for restore.
...\src\Shop\Domain\OrderService.cs(1,1): error IDE0005: Using directive is unnecessary. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0005) [...\src\Shop\Shop.csproj]
…

The IDE0005 page names the XML documentation requirement. Without GenerateDocumentationFile, the build stops with the compiler error EnableGenerateDocumentationFile and reports no finding in the code. In the case, every public member is documented. When a member lacks its comment, the build additionally reports CS1591, in the case "Missing XML comment for publicly visible type or member 'MailNotifier.NotifyCancelled(Order)'", and -warnaserror turns it into an error. A team that enables IDE0005 this way therefore documents all public members first.

Analyzer package from nuget.org

SonarAnalyzer.CSharp enters the build as a NuGet package. According to the project README, a team turns its rules on and off through .editorconfig, like those of other Roslyn analyzers. Without further configuration, the build reports five errors:

$ dotnet build Shop.slnx -warnaserror
  Determining projects to restore...
  Restored ...\src\Shop\Shop.csproj (in 284 ms).
...\src\Shop\Infrastructure\SqlOrderRepository.cs(32,9): error S2486: Handle the exception or explain in a comment why it can be ignored. [...\src\Shop\Shop.csproj]
...\src\Shop\Infrastructure\SqlOrderRepository.cs(33,9): error S108: Either remove or fill this block of code. [...\src\Shop\Shop.csproj]
...\src\Shop\Notifications\MailNotifier.cs(20,18): error S3168: Return 'Task' instead. [...\src\Shop\Shop.csproj]
...\src\Shop\Notifications\MailNotifier.cs(12,23): error S2325: Make 'NotifyShippedAsync' a static method. [...\src\Shop\Shop.csproj]
...\src\Shop\Notifications\MailNotifier.cs(20,23): error S2325: Make 'NotifyCancelled' a static method. [...\src\Shop\Shop.csproj]
  Shop -> ...\src\Shop\bin\Debug\net10.0\Shop.dll

Build FAILED.
…

The package reports the empty catch twice, as an ignored exception (S2486) and as an empty block (S108). S3168 reports async void. The layer violation, the class size, and the using stay unreported. Rule S104 reports the file OrderReport.cs only after the team sets it to warning in .editorconfig: "This file has 1417 lines, which is greater than 1000 authorized." S104 thus measures the length of the file, not the class. The file has 1,522 lines; without blank lines and without the 69 lines starting with ///, the case counts exactly 1,417. Rules S1448 and S1200, enabled in the same run, stayed silent; their thresholds were not looked up.

S2325 also flags NotifyShippedAsync from main. The package checks the whole code in the build, and with -warnaserror the build of main fails on the first day. The team fixes or suppresses such findings before it enables the package.

CodeCharter on the diff

The profile codeguard/csharp-all v1.3.0 brings rules for empty catch blocks, async void, and class size. It contains no rule for the project's layer boundary. The team stores one as the file rules/domain-boundary.ccr and lists the directory under rules: in .codecharter/config.yml:

@name "Domain must not reach infrastructure"
@severity error
@category "Architecture"
@description "Types in Shop.Domain must not depend on types in Shop.Infrastructure, directly or through other types."
@recommendation "Depend on a contract in Shop.Domain and let the infrastructure implement it."

from t in AllTypesFlattened
where t.FullName.StartsWith("Shop.Domain.")
where t.Reaches("Shop.Infrastructure.*", "declared")
select t

The article on tested architecture rules shows how to secure such a rule with hit and miss cases. In the pull request, CodeCharter checks only the changed lines with --git-ref and reports three errors with --fail-on error:

$ codecharter analyze Shop.slnx --git-ref main..HEAD --fail-on error
…
  ERROR  [ErrorHandling] Empty catch block
        catch (System.Exception)
        ...\src\Shop\Infrastructure\SqlOrderRepository.cs:32
…
  ERROR  [Async] Async void method
        Shop.Notifications.MailNotifier.NotifyCancelled
        ...\src\Shop\Notifications\MailNotifier.cs:20
…
  ERROR  [Async] Async method returns void
        Shop.Notifications.MailNotifier.NotifyCancelled
        ...\src\Shop\Notifications\MailNotifier.cs:20
…
  12 violations (3 errors, 4 warnings, 5 infos)
…

The layer violation is missing. The rule reports it at the class declaration on line 7, and the pull request did not change that line. stderr only carries a note: "Note: 7 finding(s) in diff-touched files fall outside the changed lines (…) and were NOT gated." This is the v1.7.0 behaviour. In versions after v1.7.1, --git-ref without --diff-context no longer only counts these findings: those at or above --fail-on (every one when --fail-on is not given) fail the run and are named on stderr by severity and rule; --diff-context still reports all of them, and --no-diff-context-gate restores the count-only behaviour (analyze documentation). With --fail-on error, the error-level layer violation then fails the run without --diff-context. In v1.7.0, only --diff-context includes the findings on unchanged lines of touched files:

$ codecharter analyze Shop.slnx --git-ref main..HEAD --diff-context --fail-on error
Rules: 248 from codeguard/csharp-all@1.3.0, 1 from rules
  --- Error (4) ---

  ERROR  [Architecture] Domain must not reach infrastructure
        Shop.Domain.OrderService
        ...\src\Shop\Domain\OrderService.cs:7
…
  19 violations (4 errors, 7 warnings, 8 infos)
…

In total, seven findings on unchanged lines are added: the layer violation, inject-interface-not-class on the same line, and five existing findings from main, for example a numeric literal in MailNotifier. The article on quality gates with a baseline describes how a baseline keeps such existing findings out of the gate.

CodeCharter reports the large class three times: god-class as a warning (more than 1000 lines of code and more than 30 methods), class-too-large and too-many-public-methods as info. unused-using reports the unnecessary using with severity info. With --fail-on error, none of these four findings blocks; with --fail-on warn, god-class blocks; with --fail-on info, all four block.

Project boundaries as an alternative

The layer rule is needed only while Domain and Infrastructure live in the same project. In a variant of the case, Shop.Domain and Shop.Infrastructure are separate projects, and Infrastructure references Domain. The same OrderService then does not compile:

$ dotnet build Shop.slnx -warnaserror
…
...\src\Shop.Domain\OrderService.cs(1,12): error CS0234: The type or namespace name 'Infrastructure' does not exist in the namespace 'Shop' (are you missing an assembly reference?) [...\src\Shop.Domain\Shop.Domain.csproj]
…

If someone adds the project reference from Domain to Infrastructure, the restore already fails with MSB4006: "There is a circular dependency in the target dependency graph". This holds as long as the reverse direction exists as a project reference. If both layers live in one project, or Domain may reference a third project with data access, this barrier does not apply.

Overview and duplicate findings

The table summarizes the runs; each column comes from a run of its own. The CodeCharter column applies to --git-ref --diff-context.

Defect in the pull request SDK default SDK latest-all, code style (two runs) SonarAnalyzer.CSharp default CodeCharter v1.7.0
empty catch (Exception) no finding CA1031 S2486, S108 empty-catch-block (error), generic-exception-catch (warn)
async void no finding no finding S3168 async-void, async-void-method (error), two warnings
Domain uses Infrastructure no finding no finding no finding domain-boundary (error, own rule), inject-interface-not-class (warn)
class with 34 methods no finding no finding S104 (file length) after enabling god-class (warn), two infos
unnecessary using no finding IDE0005 no finding unused-using (info)

If the team runs SonarAnalyzer and CodeCharter together, the single catch appears four times in the pull request, five times with latest-all. These counts are added up from the separate runs. Even CodeCharter alone reports async void twice as an error, because two rules of the profile hit the same method.

The team therefore assigns each kind of defect to one reporting layer. If catch and async void stay with the analyzer in the build, the local build already reports them, and CodeCharter turns off its counterparts with ignore:

ignore:
  - rule: empty-catch-block
  - rule: generic-exception-catch
  - rule: async-void
  - rule: async-void-method

With this section in .codecharter/config.yml, the same run reports 15 findings, four fewer than before, and the layer violation as the only error. The reverse route sets S2486, S108, and S3168 to none in .editorconfig. In the case, the package then reports only the two S2325 findings. The configuration documentation describes ignore with restrictions to namespaces and names.

Further tools on top of the same build also report twice. According to the JetBrains documentation (as of August 7, 2026), ReSharper InspectCode also runs the solution's Roslyn analyzers by default; --properties=RunAnalyzers=false turns that off. According to its documentation on external analyzers, SonarQube Server 2026.5 imports the findings of third-party Roslyn analyzers, including Microsoft's analyzers. The setting sonar.cs.roslyn.ignoreIssues=true turns this import off. Neither tool ran in the case.

Other tools

The following tools did not run in the case. The statements come from their documentation, read on November 12, 2026. According to its README, StyleCop.Analyzers implements the StyleCop rules as Roslyn analyzers and so belongs to the style layer next to IDE0005. Roslynator describes itself in its documentation as a set of code analysis tools for C# powered by Roslyn, with the packages Roslynator.Analyzers and Roslynator.Formatting.Analyzers and a CLI.

NDepend expresses rules as CQLinq queries over a code model; the documentation's example uses IsUsing to check dependencies between assemblies. Its quality gates make NDepend.Console.exe return a non-zero value and can refer to changes since a baseline. According to its documentation, the "Sonar way" quality gate of SonarQube Server 2026.5 evaluates new code, which in a pull request means the changes relative to the target branch. The analyzer package in the build lacks this evaluation.

Decision in the example

The tech lead keeps the SDK analyzers in their default configuration and adds SonarAnalyzer.CSharp to the build, because latest-all does not report async void in the case and brings CA1822 on main. Beforehand she fixes S2325 on NotifyShippedAsync so that main stays green. The build then reports catch and async void. She enables IDE0005 with EnforceCodeStyleInBuild, GenerateDocumentationFile, and one line in .editorconfig, because the build blocks style defects immediately with -warnaserror.

CodeCharter is meant to block layer and size, so it runs with --fail-on warn. Without a baseline, two old warnings from MailNotifier would block as well, for example one about Task.Delay bypassing TimeProvider. The tech lead therefore writes a baseline with seven findings on main and checks the pull request against it:

$ codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --git-ref main..HEAD --diff-context --fail-on warn
Rules: 248 from codeguard/csharp-all@1.3.0, 1 from rules
  --- Error (1) ---

  ERROR  [Architecture] Domain must not reach infrastructure
        Shop.Domain.OrderService
        ...\src\Shop\Domain\OrderService.cs:7
…
  10 violations (1 error, 4 warnings, 5 infos)
…

With the ignore section, this run reports only findings from the pull request, among them the layer violation and god-class, and ends with exit code 1. The unnecessary using is still reported twice, by IDE0005 and unused-using. With a fifth ignore entry for unused-using, the same run reports nine findings and leaves the using to the build.

If the team later splits Domain and Infrastructure into separate projects, the build takes over the layer boundary, and domain-boundary can go. The analysis documentation describes all options of analyze, and the article on code quality in CI pipelines covers the GitHub Actions setup.