What is a WeakReference, and when would you use one?

C# Memory Advanced 3–5 Yrs5+ Yrs Conceptual 1 min read

Quick Answer

A normal reference keeps an object alive. A WeakReference (or WeakReference<T>) lets the GC collect the object if nothing else references it — you check TryGetTarget and get null if it's gone. Used for caches that should give up memory under pressure, and for weak event handlers to avoid leaks.

A weak reference points at an object but doesn't stop the garbage collector from reclaiming it. You access it through TryGetTarget, and if the object's been collected you get null back. The two uses are: a cache that you're happy for the GC to shrink when memory is tight, so it can't leak, and weak event subscriptions so a subscriber can be collected even if it never unsubscribed from the publisher. In practice I'd usually reach for MemoryCache with explicit expiration instead, but weak references are the tool when you want the GC to make the call.

  • Cache pattern: a strong Dictionary of WeakReference<T> — entries vanish when memory is tight, so the cache can't grow unbounded.
  • ConditionalWeakTable<TKey,TValue> — attach data to an object without keeping it alive.
  • Weak events (WeakEventManager) let a subscriber be collected even if it forgot to unsubscribe.
  • Don't overuse — most caching is better done with MemoryCache and explicit size/expiration limits.