WeakReferences

A WeakReference allows you to hold a reference to an object while allowing the garbage collector to reclaim it.

What ??

Sounds strange at first, but it can be very useful. For example, you could have a rather large object created to present data to a user. You might keep a WeakReference around after you set the “strong reference” to the object to null when the user cancel’s out of the screen.

If the user were to open that screen up again, you could check the Target property of the WeakReference to see if the large object has been garbage collected yet. If the Target property is not null, you can create a new “strong reference” by setting a normal reference type variable to the WeakReference.Target property.

Since there is now a “strong reference” to the object, it will not be reclaimed by the garbage collector.

Here’s a great WeakReference blog post by Brad Abrams, which includes comments from a developer on the Microsoft CLR team.

This article Using Weak References provides details on the difference between a long and short weak reference.