WeakReference.Target Property

Definition

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

C#
public virtual object Target { get; set; }
C#
public virtual object? Target { get; set; }

Property Value

null 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.

Exceptions

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.

Examples

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.

C#
Data d = _cache[index].Target as Data;
if (d == null) {
    // If the object was reclaimed, generate a new one.
    Console.WriteLine("Regenerate object at {0}: Yes", index);
    d = new Data(index);
    _cache[index].Target = d;
    regenCount++;
}
else {
    // Object was obtained with the weak reference.
    Console.WriteLine("Regenerate object at {0}: No", index);
}

return d;

Remarks

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.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also