WeakReference
Question
Describe
WeakReferenceand when it could be useful.
Short interview answer
A
WeakReferencerefers to an object without keeping it alive for garbage collection. It can be useful for recreatable caches, but callers must handle the target being collected at any time.
Detailed answer
A WeakReference<T> lets the garbage collector reclaim its target even while the weak reference exists. It is suitable for a recreatable cache, not for an object the application requires to remain alive:
if (!previewCache.TryGetTarget(out var preview))
{
preview = CreatePreview();
previewCache.SetTarget(preview);
}
Render(preview);
The cache may contain a preview on one call and no target on the next; the code must handle both outcomes. Once preview is assigned to a local variable, that local provides the strong reference needed during rendering. Weak references do not fix accidental ownership such as an event subscription or an unbounded cache. Find and remove the unwanted strong reference first.