Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata