This documentation is archived and is not being maintained.

WeakReference.Target Property

Gets or sets the object (the target) referenced by the current WeakReference object.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public virtual Object Target { get; set; }
/** @property */
public Object get_Target ()

/** @property */
public void set_Target (Object value)

public function get Target () : Object

public function set Target (value : Object)

Not applicable.

Property Value

a null reference (Nothing in Visual Basic) if the object referenced by the current WeakReference object has been garbage collected; otherwise, a reference to the object referenced by the current WeakReference object.

Exception typeCondition


The reference to the target object is invalid. This exception can be thrown while setting this property if the value is a null reference or if the object has been finalized during the set operation.

After setting this property to the target object, make sure that there are no other strong references to the object; otherwise, it will not be collected. The object should also be set to null.

The following example tries to obtain an object from a cache of objects with weak references. If the object was reclaimed for garbage collection, a new object is generated. This example is part of a larger example provided for the WeakReference class.

// Create a short weak reference to the object.
// Specify true for a long weak reference.
WeakReference wr = new WeakReference(objA1, false);

// Set the target of the
// weak reference to the object.
wr.Target = objA1;

// Remove the strong reference
// the application has to the object.
objA1 = null;
if (objA1 == null)
    Console.WriteLine("After setting objA1 to null: objA1 is null.");

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0