📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you find and remove dead code in a large .NET codebase with confidence? Explain what analysers, code coverage, production telemetry and feature flags each tell you, and how you delete safely.

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.

Mid-Level Theory Intermediate analysers code-quality dead-code feature-flags refactoring telemetry

🎯 Key points

  • Dead code costs reading time, build time, attack surface and false matches when searching
  • Analysers find private dead code: IDE0051 unused private member, IDE0052 unread private member, IDE0060 unused parameter, CS0168/CS0219 unused locals
  • Public members can't be proven unused by the compiler: other assemblies, reflection, DI scanning, serialisation; Rider solution-wide analysis, NDepend or Visual Studio Find All References/CodeLens only cover the loaded solution
  • Code coverage, even 100%, shows what tests run, not what production runs
  • Production telemetry proves real use: Application Insights / Azure Monitor, or any OpenTelemetry backend (Grafana, Datadog), plus tombstone logs or counters
  • Stale feature flags are dead code: remove the flag and the losing branch once rollout is 100% and stable
  • Delete in small PRs; git is the backup, so don't comment code out
  • Choose the observation window from the business calendar (EOFY, quarterly BAS) before deleting rare paths

⏱ 30-second answer

Dead code isn't free: it slows reading, builds and reviews, widens the attack surface and misleads searches. Finding it takes layers of evidence:

  • Analysers prove private code is unused: IDE0051 (unused private member), IDE0052 (unread private member), IDE0060 (unused parameter). Rider's solution-wide analysis or NDepend extend this to public members inside the solution.
  • Telemetry proves what production runs: endpoint request counts in Application Insights, or a tombstone log you add to suspect code and watch for a full business cycle.
  • Coverage only shows what tests run, so it finds candidates, not proof.
  • Feature flags at 100% for weeks are dead branches waiting to be deleted.

Then delete in small PRs; git is the backup. The trade-off: proving something unused takes time, so match the evidence to the risk.

🗣 Full answer (senior)

How I would answer this in an interview

"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 .editorconfig and 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."


What each source of evidence tells you

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

Things the compiler can't see

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

Production example

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.

🔍 What the interviewer is checking

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

  • Names specific analyser rules for private dead code
  • Knows coverage measures tests, not production
  • Uses telemetry or tombstones for public and rare paths
  • Removes stale feature flags with their branches
  • Deletes in small, revertible PRs

Red flags

  • Comments code out 'just in case'
  • Deletes public code based on IDE 'no references' alone
  • Never deletes anything because it might be used

📚 Learn in depth

1. Why dead code accumulates

 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.

2. How the analysers work

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

3. Coverage is about tests

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.

4. Telemetry and tombstones

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.

5. Feature flags

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.

6. Deleting safely

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.

Try it yourself

  1. Set IDE0051 and IDE0052 to warning, build with EnforceCodeStyleInBuild=true, and count the warnings.
  2. Run dotnet test --collect:"XPlat Code Coverage" and list types with 0% coverage as candidates.
  3. Query Application Insights for endpoints with zero requests in 90 days.
  4. Add a tombstone counter to one suspect method and plan the observation window around your business calendar.
  5. Find a feature flag that's been at 100% for a month and remove it.

💻 Code

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

⚠ Common mistakes

  • Mistake: Commenting code out instead of deleting it. Why it is wrong: commented code isn't compiled or tested, rots immediately and clutters reading. Instead: delete it; git history keeps it.
  • Mistake: Treating 0% test coverage as proof that code is unused. Why it is wrong: coverage measures tests, not production. Instead: use coverage for candidates, telemetry for proof.
  • Mistake: Trusting "no references" in the IDE for public members. Why it is wrong: reflection, DI scanning, serialisation, scheduled jobs and other repositories are invisible. Instead: search for string usages and gather production evidence.
  • Mistake: Using a two-week telemetry window. Why it is wrong: code for EOFY, quarterly BAS or annual rate changes looks dead most of the year. Instead: choose the window from the business calendar.
  • Mistake: Leaving feature flags in place after full rollout. Why it is wrong: both paths stay alive, tests double and the losing branch rots. Instead: give each flag an owner and expiry; remove flag and branch together.
  • Mistake: Deleting a large area in one PR. Why it is wrong: if something breaks, the revert is large and drags unrelated deletions with it. Instead: small PRs, one area each.
  • Mistake: Removing a public API endpoint without notice. Why it is wrong: external consumers break. Instead: deprecate (Deprecation/Sunset headers), watch traffic fall to zero, then remove.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions code kept 'in case we need it later' Why: Checks they apply YAGNI to keeping code as well as writing it
    How to answer

    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.

  2. When: Candidate talks about feature flags and rollouts Why: Checks they can run a flagged rollout to completion, which is when the flag becomes removable
    How to answer

    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.

  3. When: Candidate sets analyser severity in .editorconfig Why: Checks they know how to enforce code-style rules in the build, not only in the IDE
    How to answer

    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.

🛠 Real-world problems: how you handle them

Deleting a 'dead' export that only ran at end of financial year
Situation
A billing monolith of [size] had dozens of methods suspected dead. A clean-up PR deleted a CSV export with no callers in the solution and no traffic in the last [30] days.
Signals
On [early July], the finance team's EOFY reconciliation job failed with a 404: the export was called once a year by a scheduled job configured outside the repository.
Investigation
Checked Application Insights for historical requests to the endpoint over 13 months (one burst each July), found the job definition in [scheduler], and used git log to find the deleting PR.
Resolution
Reverted the single small PR, re-ran the export for finance the same day, then documented the job and added a contract test for the endpoint.
Prevention
Tombstones with observation windows chosen from the business calendar, an inventory of external scheduled jobs, deprecation headers before removing endpoints, and a checklist item to check 13 months of telemetry for endpoints.

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]%.

↩ Usually asked after

More in Refactoring

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me