O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

WeakReference

Synopsis

This class encapsulates a weak reference to an object. By default, when you instantiate a .NET class, you create a strong reference, which prevents the garbage collector from removing the object and reclaiming memory. A weak reference, however, does not prevent an object from being released.

Objects that are weakly referenced can still be kept alive as long as there is at least one strong reference to them. That means a weak reference allows you to access an object as long is it in use by another part of your application. For example, objects can be stored in a collection using a weak reference, but not kept alive just because they are in the collection.

To create a weakly referenced object, pass the name of the object to the WeakReference constructor. You can use the IsAlive property to check if the reference is valid, and the Target property to get a reference to the actual object. Assigning the Target property to another variable creates a strong reference.

You can set the TrackResurrection property to true in the constructor to maintain a long weak reference, which tracks an object during (or after) finalization.

public class WeakReference : System.Runtime.Serialization.ISerializable {
// Public Constructors
   public method WeakReference(object target);  
   public method WeakReference(object target, 
        bool trackResurrection);  
// Protected Constructors
   protected method WeakReference(
        System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required