Covers how SonarQube Server and SonarQube Cloud analyse .NET code with the scanner, how quality gates and the new-code period work, edition differences for branch and pull request analysis, coverage import, and how to avoid metric gaming.
SonarQube runs in CI: the dotnet-sonarscanner wraps your build (begin → dotnet build → dotnet test → end), collects Roslyn analyser results plus imported coverage, and the server stores issues over time.
A quality gate is a set of pass/fail conditions. The default Sonar way gate looks only at new code: no new issues, every new security hotspot reviewed, at least 80% coverage on new lines, at most 3% duplication. The new code period (previous version, N days or a reference branch) is what makes legacy code adoptable: you don't fix the past, you stop making it worse.
The Community Build only analyses the main branch; pull request decoration needs Developer Edition or above, or SonarQube Cloud.
Trade-off: gates focus attention, but once a number becomes a target people game it (assert-free tests, bulk Won't fix), so keep few conditions and review how issues are resolved.
"SonarQube is a platform on top of static analysis. For C# it uses its own Roslyn analysers, so in the pipeline you run
dotnet sonarscanner begin, then the normaldotnet buildanddotnet testwith coverage, thendotnet sonarscanner end, which uploads everything. The server keeps the history: every issue, when it appeared, who resolved it and how. Coverage isn't measured by Sonar; you produce an OpenCover or Visual Studio coverage file with coverlet ordotnet-coverageand point the scanner at it.The part that matters most is the quality gate and the new code focus. A quality gate is a list of conditions that turns the analysis into a pass or fail, and you make that a required check on the pull request. The default gate is about new code: no new issues, new security hotspots reviewed, 80% coverage on changed lines, low duplication. 'New code' is defined per project, usually as changes since the previous version or compared with the main branch. That's what makes it usable on a ten-year-old codebase: nobody has to fix 6,000 old issues, but every PR has to leave the code it touches clean. Editions matter here. The free Community Build only analyses the main branch, so you can't gate pull requests; branch and PR analysis with decoration starts at Developer Edition, and SonarQube Cloud includes it.
The mistake I see is managing by the dashboard: a manager sets 'coverage must reach 85%' and soon there are tests that call methods with no asserts, and issues bulk-marked Won't fix. I keep the gate to a few conditions the team agreed, I review resolutions in the PR, and I treat the numbers as prompts for a conversation, not a scorecard."
| Piece | What it does | Where you set it |
|---|---|---|
| Scanner for .NET | Hooks MSBuild, runs Sonar's Roslyn rules, uploads results | Pipeline step |
| Quality profile | Which rules are active for C# | Server, per language |
| Quality gate | Pass/fail conditions on the analysis | Server, per project |
| New code definition | Which lines count as 'new' | Project settings |
| Coverage import | Reads coverlet / dotnet-coverage reports | Scanner parameters |
| PR decoration | Posts the gate result and issues on the PR | DevOps platform integration |
| Product | Branch / PR analysis | Notes |
|---|---|---|
| SonarQube Community Build | No: main branch only | Free, self-hosted |
| SonarQube Server Developer Edition | Yes, with PR decoration | Paid, priced by lines of code |
| Enterprise / Data Center | Yes | Portfolios, reports, high availability |
| SonarQube Cloud | Yes | SaaS; free for public projects, paid plans for private code |
| Gaming pattern | Counter |
|---|---|
| Tests that execute code without asserting | Review tests in PRs, mutation testing (Stryker.NET) on core modules |
| Bulk Won't fix / False positive | Restrict who can resolve, review resolutions weekly |
Wide sonar.exclusions |
Exclusions changed only by PR with a reason |
| Splitting PRs to dodge conditions | Gate on overall new code, not per-PR thresholds alone |
On an invoicing platform of roughly [400k] lines, we started with the gate on new code only. Over six months the old issue count fell from [6,200] to [4,100] purely because touched files were cleaned, with no 'clean-up sprint', and the PR gate failed on about 1 in 12 PRs, almost always for missing tests on new branches of logic.
Checks whether the candidate can use SonarQube as a delivery tool (gates on new code, PR checks) rather than as a vanity dashboard.
Green flags
Red flags
dotnet sonarscanner begin /k:"billing-api" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml"
│ writes MSBuild targets that inject Sonar's analysers and settings
▼
dotnet build ──► Roslyn runs SonarAnalyzer.CSharp + your analysers ──► results to .sonarqube/
▼
dotnet test --collect:"XPlat Code Coverage" ──► coverage files
▼
dotnet sonarscanner end ──► uploads results + coverage ──► server computes metrics and the gate
Because it hooks the build, the scanner cannot analyse C# without building it. A dotnet build --no-restore that is skipped or cached breaks the analysis, which is a common pipeline fault.
The new code period decides which lines are measured by the gate:
| Definition | Good for |
|---|---|
| Previous version | Teams that release with version numbers |
| Number of days (e.g. 30) | Continuous delivery without versions |
Reference branch (main) |
Feature branches and PRs |
| Specific analysis | A one-off baseline after a big change |
Lines are attributed using SCM blame, so the scanner needs full git history (fetch-depth: 0 in GitHub Actions) or new code is computed wrongly.
Sonar does not run tests. You produce coverage with coverlet (--collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover) or dotnet-coverage collect -f xml, then pass sonar.cs.opencover.reportsPaths or sonar.cs.vscoveragexml.reportsPaths. Missing coverage shows as 0%, not as an error, so always check the report path.
When a measure becomes a target it stops being a good measure. Coverage measures executed lines, not verified behaviour; the duplication metric can be lowered by bad abstractions. Keep the gate small and pair it with human review.
docker run -p 9000:9000 sonarqube:community), analyse a sample API and look at the issues view.A GitHub Actions job that builds, tests with coverage and runs the SonarQube Cloud scanner; the gate result becomes a required PR check.
# .github/workflows/sonar.yml
name: sonar
on:
pull_request:
push:
branches: [main]
jobs:
analyse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history: needed for new-code and blame
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- run: dotnet tool install --global dotnet-sonarscanner
- name: Build, test and analyse
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: |
dotnet sonarscanner begin /k:"acme_billing-api" /o:"acme" \
/d:sonar.host.url="https://sonarcloud.io" \
/d:sonar.token="$SONAR_TOKEN" \
/d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" \
/d:sonar.qualitygate.wait=true
dotnet build Billing.slnx -c Release
dotnet test Billing.slnx -c Release --no-build \
--collect:"XPlat Code Coverage" \
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover
dotnet sonarscanner end /d:sonar.token="$SONAR_TOKEN"
A test that games coverage versus one that earns it:
namespace Billing.Tests;
public class GstCalculatorTests
{
[Fact] // Before: raises coverage, verifies nothing
public void Calculate_runs() => new GstCalculator().Calculate(100m);
[Theory] // After: the same lines covered, behaviour checked
[InlineData(100.00, 10.00)]
[InlineData(0.05, 0.01)] // rounding: AwayFromZero to the cent
public void Calculate_returns_ten_percent_rounded(decimal net, decimal expected) =>
Assert.Equal(expected, new GstCalculator().Calculate(net));
}
public sealed class GstCalculator
{
public decimal Calculate(decimal net) =>
Math.Round(net * 0.10m, 2, MidpointRounding.AwayFromZero);
}
fetch-depth: 0.sonar.qualitygate.wait=true and make the check required.The gate is a team agreement, not a tool setting. I'd agree three or four conditions with the team, make them a required PR check, and change them only through a retro. Everything else on the dashboard is information. The new-code approach is the only one I've seen work on large legacy systems, because it aligns the cost of improvement with work that is already happening.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SDK analysers + .editorconfig only |
Small team, simple pipeline | Free | When you need history or PR-level gates across many repos |
| SonarQube Community Build | Want dashboards, main-branch history | Self-hosting, no PR gate | When the PR gate is the main goal |
| SonarQube Server Developer+ | Self-hosted, data must stay in your network (e.g. Azure Australia East VM) | Licence by LOC + ops | Few repos, no hosting skills |
| SonarQube Cloud | GitHub / Azure DevOps teams, quick start | Subscription; code analysed in vendor cloud | Data residency rules forbid it |
The file under review turns on TreatWarningsAsErrors and then hides 25 warnings with NoWarn. That list includes nullable warnings, obsolete-API warnings and a security rule, so the policy looks strict while silencing the warnings that matter most. I'd remove those suppressions. Rules that genuinely don't apply would get a severity in .editorconfig, scoped to the right folders and commented. Rules we can't fix yet would go in WarningsNotAsErrors, so they stay visible as warnings. I'd also pin AnalysisLevel so an SDK upgrade can't break the build overnight, apply the same settings locally and in CI, and ratchet a legacy codebase towards zero warnings rather than flipping everything at once.
Separate generated or declarative files from code with behaviour. EF Core migrations, *.Designer.cs and model snapshots are generated: exclude them from coverage only with sonar.coverage.exclusions (e.g. **/Migrations/**), keep them in analysis, and record why in the repo. Plain DTOs (records with properties) usually have no logic worth testing; if they're failing the gate, check whether they actually contain validation, mapping or computed properties. If they do, that logic needs tests (validator tests, mapping tests), and it may belong in a validator or mapper rather than the DTO. Don't lower the threshold for everything; change exclusions only through a reviewed PR.
Dead code isn't free: it slows reading, builds and reviews, widens the attack surface and misleads searches. Finding it takes layers of evidence:
public members inside the solution.Then delete in small PRs; git is the backup. The trade-off: proving something unused takes time, so match the evidence to the risk.
How to tell it (STAR)
**S:** At [company] our SonarQube gate demanded 85% overall coverage on a [300k]-line billing API, so it failed on every PR and had been made optional. **T:** I was asked to get quality gating working again without stopping delivery. **A:** I showed the team that coverage had risen while mutation score on pricing was [38%], switched the gate to new-code conditions, made it required, and restricted bulk resolutions. **R:** The gate passed on [92%] of PRs first time within a month, and we had [zero] pricing regressions in the next [two] quarters.
Last updated 23 Nov 2026.