Advertisement

Memory & Garbage Collection interview questions and answers

18 Memory & Garbage Collection interview questions for C# roles, each with a model answer, examples and likely follow-ups.

18 questions
Advertisement

18 questions

Q11 Intermediate Save

What is boxing and unboxing, and why does it have a real performance cost?

Boxing converts a VALUE TYPE into a reference-type object (wrapping it in a heap-allocated box) implicitly whenever a value type is used where 'object' (or an interface) is expected; unboxing converts it back. Both involve a HEAP ALLOCATION (for boxing) and a COPY operation, which is measurably slower than working with the value type directly, especially in tight loops.
int number = 42;
object boxed = number;        // boxing: heap allocation, copies the int into a new object
int unboxed = (int)boxed;     // unboxing: copies the value back out

// Generics avoid this entirely:
List<int> numbers = new();    // no boxing -- List<int> stores actual ints, not boxed objects
Real-world example
Understanding why using a non-generic ArrayList (which stores everything as 'object') is significantly slower than a generic List<int> for value types.
Likely follow-ups
  • How do generics specifically eliminate the need for boxing in scenarios where non-generic collections would require it?
Generics
Q12 Advanced Save

How does the difference between the Server GC and Workstation GC modes affect a .NET application's throughput and latency characteristics?

Workstation GC (the default for client apps) optimizes for LOW LATENCY, running collections on a single thread with minimal pause impact on a UI thread; Server GC (typical for ASP.NET Core web servers) optimizes for HIGH THROUGHPUT by using MULTIPLE dedicated GC threads (one per CPU core) and separate heaps, trading slightly higher pause times for much better overall performance under heavy concurrent load.
// runtimeconfig.json or .csproj setting
<PropertyGroup>
  <ServerGarbageCollection>true</ServerGarbageCollection>
</PropertyGroup>
// ASP.NET Core apps typically benefit from Server GC due to high, concurrent allocation rates
Real-world example
Choosing Server GC for a high-throughput web API versus Workstation GC (with concurrent GC enabled) for a responsive desktop application.
Likely follow-ups
  • Why might Server GC actually be a poor choice for a container with a very LOW CPU core limit?
Multithreading & Task Parallel Library
Q13 Advanced Save

How would you use a memory profiler (or dotnet-counters / dotnet-gcdump) to diagnose excessive garbage collection pressure in a production .NET application?

Tools like dotnet-counters can monitor real-time GC metrics (Gen 0/1/2 collection counts, allocation rate, time in GC) to identify if GC pressure is a genuine bottleneck; dotnet-gcdump captures a full heap snapshot for offline analysis, letting you identify which object types are consuming the most memory or being allocated at the highest rate, pointing directly at the code responsible.
# Monitor live GC metrics
dotnet-counters monitor -p <process-id> --counters System.Runtime

# Capture a heap dump for detailed offline analysis
dotnet-gcdump collect -p <process-id>
Real-world example
Diagnosing a production API experiencing intermittent latency spikes, traced back to frequent Gen 2 collections caused by excessive large object allocations.
Likely follow-ups
  • What specific GC-related metric would most directly indicate that allocation rate itself (not object retention) is the core problem?
Debugging Testing & Tooling
Q14 Advanced Save

What is the Large Object Heap (LOH), and why do objects allocated there behave differently from regular small objects?

Objects 85,000 bytes or larger are allocated on a SEPARATE Large Object Heap, which is NOT compacted by default during garbage collection (unlike the regular generational heap) — this can lead to HEAP FRAGMENTATION over time as large objects are freed and re-allocated, since the LOH's free space between surviving large objects can't always be reused efficiently.
byte[] largeArray = new byte[100_000]; // allocated on the LOH, not the regular generational heap
// Repeatedly allocating/freeing large arrays like this can fragment the LOH over time

// Mitigation: enable LOH compaction explicitly when needed
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
Real-world example
Diagnosing a long-running service's gradually increasing memory footprint traced to LOH fragmentation from repeated large buffer allocations.
Likely follow-ups
  • How does using ArrayPool<T> help avoid the repeated large allocations that cause this LOH fragmentation problem in the first place?
Arrays Span<T> & Memory<T>
Q15 Advanced Save

How do WeakReference<T> objects work, and in what scenario would you use one instead of a normal strong reference?

WeakReference<T> holds a reference to an object WITHOUT preventing the garbage collector from reclaiming it — calling .TryGetTarget() returns the object if it's still alive, or fails gracefully if it's already been collected, useful for caches or event subscriptions where you want to reference something WITHOUT being the reason it stays alive.
var cache = new Dictionary<string, WeakReference<LargeObject>>();
cache["key"] = new WeakReference<LargeObject>(new LargeObject());

if (cache["key"].TryGetTarget(out var obj)) {
  UseObject(obj); // still alive
} else {
  // was collected -- recreate or fetch it again
}
Real-world example
Building a memory-sensitive cache that lets the GC reclaim cached items under memory pressure, rather than holding them alive indefinitely.
Likely follow-ups
  • How does WeakReference<T> relate conceptually to how WeakMap/WeakSet work in JavaScript?
Collections
Q16 Advanced Save

How would you use ArrayPool<T> to reduce garbage collection pressure in a high-throughput, buffer-allocating hot path?

ArrayPool<T>.Shared provides a pool of reusable arrays — instead of allocating a new array every time you need a temporary buffer (and letting the GC collect it shortly after), you RENT an array from the pool, use it, and RETURN it when done, dramatically reducing allocation rate and GC pressure in code that repeatedly needs similarly-sized temporary buffers.
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096); // rent instead of 'new byte[4096]'
try {
  int bytesRead = stream.Read(buffer, 0, 4096);
  ProcessData(buffer, bytesRead);
} finally {
  ArrayPool<byte>.Shared.Return(buffer); // return it for reuse, reducing future allocations
}
Real-world example
Reducing GC pressure in a high-throughput network server or file-processing pipeline that constantly needs similarly-sized temporary buffers.
Likely follow-ups
  • Why must you be careful about the RETURNED array's contents, given ArrayPool doesn't automatically clear it by default?
Arrays Span<T> & Memory<T>
Q17 Beginner Save

How does garbage collection in .NET work, and what three phases does a collection cycle go through?

The .NET garbage collector automatically reclaims memory occupied by objects no longer reachable by the application, removing the need for manual memory management -- a collection cycle generally proceeds through marking (scanning the object graph from GC roots to determine which objects are still reachable), sweeping (reclaiming the memory of unreachable objects), and compacting (moving surviving objects together to reduce fragmentation and keep allocation fast) -- this automation prevents most memory leaks but means the GC can introduce brief pauses, especially if an application allocates large numbers of short-lived objects.
public void ProcessOrders() {
    for (int i = 0; i < 100_000; i++) {
        var temp = new OrderDto(); // short-lived object, becomes eligible for GC almost immediately
        // process temp
    } // by the time this loop ends, most 'temp' instances are already unreachable garbage
}
Real-world example
A high-throughput API creating a new DTO object per request notices periodic latency spikes correlated with GC cycles, prompting the team to reduce unnecessary allocations (pooling objects, using structs for small data) to shrink the frequency and cost of those collection pauses.
Likely follow-ups
  • What specific techniques reduce GC pressure in an allocation-heavy hot path?
  • How do GC generations (Gen 0/1/2) affect how often a given object actually gets collected?
Garbage Collection Diagnostics & Performance
Q18 Intermediate Save

What is the difference between Dispose and Finalize in C#, and when should each actually be used?

Dispose (part of IDisposable) provides deterministic, explicit cleanup of unmanaged resources -- you call it yourself (typically via a using statement) as soon as you're done with an object, rather than waiting for garbage collection. Finalize (implemented via a destructor, ~ClassName()) is invoked automatically and non-deterministically by the garbage collector as a last-resort safety net before an object's memory is reclaimed, but finalizers add real overhead to GC (finalizable objects require an extra collection pass), so a class implementing IDisposable should call GC.SuppressFinalize(this) inside Dispose to skip the unnecessary finalizer call once cleanup has already happened deterministically.
public class ResourceHandler : IDisposable {
    public void Dispose() {
        Console.WriteLine("Dispose called - resources freed.");
        GC.SuppressFinalize(this); // skip the now-unnecessary finalizer
    }
    ~ResourceHandler() {
        Console.WriteLine("Finalizer called by GC - backup cleanup only.");
    }
}

using (var handler = new ResourceHandler()) {
    // use the resource
} // Dispose() is called automatically here, at a known, predictable point
Real-world example
A database connection wrapper implements IDisposable so the connection is always closed deterministically at the end of a using block, while its finalizer exists purely as a safety net catching the rare case where a caller forgot to dispose it properly.
Likely follow-ups
  • What happens to an object's finalizer if Dispose() is never called at all?
  • Why does the 'using' statement generate a try/finally block under the hood?
Error Handling Garbage Collection

Showing 11–18 of 18