Covers finding dead code with compiler and IDE analysers (IDE0051, IDE0052, IDE0060), solution-wide analysis, coverage and production telemetry, removing stale feature flags, and a safe deletion process with tombstones and small reversible PRs.
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.
"I treat dead code as a cost, not as harmless clutter. Every unused method still gets read, compiled, reviewed when someone renames something, and scanned for vulnerabilities. And it lies: someone searches for where GST is calculated and finds the old method nobody calls.
The question is how confident I can be that something is unused, and that depends on its visibility. For private members, the compiler can prove it: IDE0051 flags unused private members, IDE0052 private fields that are written but never read, IDE0060 unused parameters, and CS0168 and CS0219 unused locals. I set those to warning in
.editorconfigand the IDE removes them safely. For public code inside our own solution, Rider's solution-wide analysis or NDepend can show members with no callers, but the compiler can't see reflection, DI assembly scanning, serialisation, or another repository that references our NuGet package.So for anything public or anything that might be called from outside, I want production evidence. If it's an endpoint, Application Insights request counts over a full business cycle, and in Australia that often means waiting past end of financial year, because some code only runs at EOFY. If it's an internal path, I add a tombstone: a log line or counter that fires if the code ever runs, ship it, and wait. Coverage helps find candidates, but it only says what the tests run.
Feature flags are the biggest source. Once a flag has been at 100% and stable for a few weeks, I delete the flag and the losing branch in one PR.
The mistake I see is commenting code out 'in case'. Git already keeps it. Delete it in a small PR that's easy to revert."
| Evidence | Proves | Doesn't prove | Effort |
|---|---|---|---|
| Compiler/IDE analysers (IDE0051, IDE0052, IDE0060) | Private member/parameter unused | Anything public | Seconds |
| Solution-wide analysis (Rider, NDepend) | No callers inside the solution | Reflection, other repos, DI scanning | Minutes |
| Code coverage (coverlet, dotnet-coverage) | What tests execute | What production executes | Minutes |
| Telemetry (App Insights, logs, metrics) | Not called in the observation window | Rare paths outside the window | Days to months |
| Tombstone (log/counter on suspect code) | Not executed in production since shipping | Paths in other deployments | One deploy + waiting |
| Feature flag state | Losing branch is unreachable | That the flag isn't read elsewhere | Check flag service |
| Hidden caller | Example | How to check |
|---|---|---|
| Reflection | Activator.CreateInstance(typeName) |
Search for the type name as a string |
| DI assembly scanning | Scrutor .AddClasses() |
Check registrations and start-up logs |
| Serialisation | DTO property only set by JSON | API contract tests |
| Scheduled jobs | Hangfire/Quartz job by name | Job dashboards, cron config |
| Other repos | NuGet consumers | Package download stats, ask consumers |
| Rare business events | EOFY, leap year, 1 July rate changes | Telemetry across a full cycle |
In a 400k-line billing monolith, enabling IDE0051/IDE0052 as warnings removed about 3,000 lines of private dead code in one afternoon. Tombstone counters on 40 suspect public methods ran for one quarter including EOFY; 33 never fired and were deleted in 11 small PRs (about 18,000 lines), build time dropped 12%, and none had to be restored.
Checks that the candidate can delete code safely, using the right evidence for each visibility level, rather than leaving clutter or deleting recklessly.
Green flags
Red flags
feature flag added -> rollout 100% -> flag never removed -> dead branch
endpoint replaced (v2) -> v1 kept 'for safety' -> no callers left
refactoring leaves old helper -> nobody sure it's unused -> stays
Each is cheap to leave and slightly scary to delete, so it compounds. The cure is making deletion cheap and evidence easy to get.
Unused-member analysis is a reference search over the compilation. For private members the whole universe of possible callers is the containing type (plus nested types and partials), so Roslyn can prove there are none: IDE0051 reports private methods, fields and properties with no references; IDE0052 reports private fields assigned but never read. internal members widen the universe to the assembly plus InternalsVisibleTo friends; public widens it to everything, which no single compilation can see. That's why the built-in rules stop at private.
IDE rules are reported in the IDE by default; to fail the build, set severity in .editorconfig and enable EnforceCodeStyleInBuild:
[*.cs]
dotnet_diagnostic.IDE0051.severity = warning
dotnet_diagnostic.IDE0052.severity = warning
dotnet_diagnostic.IDE0060.severity = warning
Coverage tools (coverlet, dotnet-coverage) instrument the code and record which lines the test run executed. 0% coverage on a method means no test calls it; production might call it every second. It's useful for building a candidate list, not for deleting.
For endpoints, request telemetry already exists: in Application Insights, requests | summarize count() by name over 90 days. For internal paths, add a tombstone: a cheap log or Counter<long> increment with a unique name in the suspect code. If it never fires over a full business cycle, delete. Choose the window by the business calendar (monthly billing, quarterly BAS, EOFY on 30 June), not a fixed number of days.
With Microsoft.FeatureManagement, a flag at 100% still costs a check and keeps two code paths alive. Track flags with an owner and expiry date; when it expires, delete the flag definition, every IsEnabledAsync call and the losing branch together.
Small PRs, one area each; run the full test suite and a solution-wide build (including other solutions that reference the code); deploy; keep the PR easy to revert. Don't comment out: commented code isn't compiled, so it silently rots and is never safe to restore anyway.
EnforceCodeStyleInBuild=true, and count the warnings.dotnet test --collect:"XPlat Code Coverage" and list types with 0% coverage as candidates.A tombstone: record if suspect code ever runs, without changing its behaviour.
namespace Billing;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.Logging;
public sealed class Tombstones(IMeterFactory meterFactory, ILogger<Tombstones> logger)
{
private readonly Counter<long> _hits =
meterFactory.Create("Billing.Tombstones").CreateCounter<long>("billing.tombstone.hits");
// Call at the top of code you believe is dead. If the dashboard stays at zero
// for a full business cycle (including EOFY), delete the code.
public void Hit(string id)
{
_hits.Add(1, new KeyValuePair<string, object?>("tombstone.id", id));
logger.LogWarning("Tombstone {TombstoneId} hit", id);
}
}
public sealed class LegacyInvoiceExporter(Tombstones tombstones)
{
public string ExportCsvV1(IEnumerable<decimal> totals)
{
tombstones.Hit("invoice-export-csv-v1"); // added 2026-11-01, review after EOFY
return string.Join(",", totals);
}
}
Removing a stale feature flag: before and after.
namespace Billing;
using Microsoft.FeatureManagement;
public interface IPricingEngine { decimal Price(decimal amount); }
public sealed class CheckoutBefore(IFeatureManager features, IPricingEngine oldEngine, IPricingEngine newEngine)
{
public async Task<decimal> PriceAsync(decimal amount, CancellationToken ct)
{
// Flag has been at 100% since the 1 July rollout.
if (await features.IsEnabledAsync("NewPricingEngine"))
return newEngine.Price(amount);
return oldEngine.Price(amount);
}
}
// After: flag, losing branch and the old engine's registration deleted in one PR.
public sealed class Checkout(IPricingEngine engine)
{
public decimal Price(decimal amount) => engine.Price(amount);
}
// Application Insights: endpoints with no traffic in the last 90 days are candidates
requests
| where timestamp > ago(90d)
| summarize calls = count() by name
| order by calls asc
Deprecation/Sunset headers), watch traffic fall to zero, then remove.The senior move is making deletion routine: analysers that flag private dead code in the build, flags with expiry dates, and tombstones as a normal tool. Then the scary "is this used?" question becomes a dashboard check rather than an archaeology project.
Match the evidence to the blast radius. A private helper needs nothing but the analyser; a public endpoint used by partners needs telemetry over a full cycle and a deprecation notice.
| Code | Evidence needed | Typical wait | When not to delete |
|---|---|---|---|
| Private member | IDE0051/IDE0052 | None | Never: just delete |
| Internal/public in solution | Solution-wide analysis + string search | None to a sprint | Reflection or DI scanning involved |
| Endpoint / message handler | Telemetry, consumer check, deprecation | One business cycle | Contractual or regulatory obligation to keep it |
| Rare business path (EOFY) | Tombstone across the event | Up to a year | Unsure of the business calendar: ask finance |
YAGNI (You Aren't Gonna Need It, from Extreme Programming) says do not build a capability until you actually need it. Speculative features cost time to build, delay what is needed now, add code to maintain, and are often wrong when the real requirement arrives. YAGNI does not mean skipping tests or refactoring; it is those practices that make adding the feature later cheap. I make an exception for decisions that are expensive to reverse, such as public API contracts, persisted data formats and security, where some upfront design pays off.
Treat each step as a controlled experiment. Before starting, agree the promotion and rollback criteria: the SLIs for the affected endpoints (error ratio, p95 latency, one business metric such as checkout conversion), the thresholds and the minimum sample size. Use a targeting filter (hashed user id) so users stay in their cohort, and tag telemetry with the flag variant (an Application Insights custom dimension or OpenTelemetry attribute) so a KQL query or dashboard compares the new cohort against the control cohort in the same time window. Step 1% → 10% → 50% → 100%, holding each step through a peak period. If the treatment cohort is worse beyond the threshold, turn the flag off, automatically from an alert or by runbook. The trade-off: small steps are safe but need longer holds to gather enough traffic to be significant.
I commit an .editorconfig at the repo root with root = true. It holds formatting (indentation, new lines), .NET code style preferences such as file-scoped namespaces, and severities for analyser and code style rules via dotnet_diagnostic.<id>.severity. Visual Studio, VS Code and Rider all read it, so style no longer depends on the editor. To enforce it, I set EnforceCodeStyleInBuild so IDE rules run during dotnet build, and run dotnet format --verify-no-changes in CI.
How to tell it (STAR)
**S:** We were cleaning dead code from a billing monolith, and a PR deleted an export endpoint with no callers and no traffic for 30 days. **T:** When finance's EOFY job broke, I had to restore it fast and fix how we decided what was dead. **A:** Because the deletion was its own small PR, I reverted it within [minutes] and finance re-ran the job. I then queried 13 months of request telemetry, found the yearly pattern, and changed our process: tombstones with windows based on the business calendar, plus a register of external jobs. **R:** Over the next [quarter] we deleted [n] lines across [n] PRs with zero further restores, and build time dropped [x]%.
Last updated 23 Nov 2026.