/// Points to data that can be garbage collected any time.
static WeakReference _weak;
static void Main()
// Assign the WeakReference.
_weak = new WeakReference(new StringBuilder("perls"));
// See if weak reference is alive.
Console.WriteLine((_weak.Target as StringBuilder).ToString());
// Invoke GC.Collect.
// ... If this is commented out, the next condition will evaluate true.
// Check alive.
A discussion. Is using the WeakReference type a good idea? Unfortunately, the behavior of the garbage collector is not always predictable and can even vary when the runtime is updated.
Also Using caches that are too large will cause reductions in performance because of memory locality degradation.
Thus WeakReference is often not ideal for performance work. A time-based expiration scheme would be more effective.
A review. WeakReference influences the GC. When a collection is done, either forced or invoked by the runtime, objects that are only referenced through WeakReference can be collected.
Therefore, you must check these objects for life upon each access. The IsAlive method is used for this purpose—it makes code more complex.