Advertisement
Advanced C#, Memory & Garbage Collection

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

Short answer

WeakReference 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…

Save C# mock interview
Advertisement
AModel answer
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?
Related topics