.NET Developer interview question

How does garbage collection work in .NET?

.NET GC allocates managed objects in generations, traces reachable objects from roots, compacts eligible heaps, and treats large objects separately. Allocation rate, retention, finalizers and pauses should be measured before tuning.

Direct answer

What a strong answer covers

How it works

The .NET GC is generational: new objects land in gen 0, survivors are promoted to gen 1 and then gen 2, and objects above 85 KB go to the large object heap, which is collected only with gen 2. Gen 0 collections are frequent and cheap; gen 2 collections are rare and can pause for longer, especially in server mode with large heaps. Allocation rate drives gen 0 frequency, retention drives promotion, and finalisers delay reclamation by a full cycle. Server GC uses one heap per core for throughput; workstation GC favours latency on desktops. Decisions come from dotnet-counters and traces, not from defaults chosen blindly.

Example

An API with periodic 300 ms pauses showed gen 2 collections every minute in dotnet-counters; the cause was a per-request byte array of 100 KB landing on the large object heap. Renting from ArrayPool eliminated the LOH churn and the pauses. A second service allocated 2 GB per second of short-lived strings from logging interpolation, fixed by structured logging with message templates.

Common mistakes

  • Calling GC.Collect from application code to fix a leak.
  • Ignoring the large object heap when allocating big buffers per request.
  • Switching to server GC on a memory-constrained container and getting killed for exceeding limits.

A useful answer structure

Answer from your own work.

Do not memorise a script: use only examples you can explain honestly in follow-up questions.

Practise this answer with MiraHint

Open the desktop workspace and rehearse a clear answer in your own words.

Download MiraHint
.NET Developer interview questions