views:

632

answers:

4

I would like to keep a list of a certain class of objects in my application. But I still want the object to be garbage collected. Can you create weak references in .NET?

For reference:

Answer From MSDN:

To establish a weak reference with an object, you create a WeakReference using the instance of the object to be tracked. You then set the Target property to that object and set the object to null. For a code example, see WeakReference in the class library.

+10  A: 

Yes, there's a generic weak reference class.

MSDN > Weak Reference

arul
+5  A: 

Can you create weak references in .NET?

Yes:

WeakReference r = new WeakReference(obj);

Uses System.WeakReference.

Konrad Rudolph
+4  A: 

Yes...

There is a pretty good example to be found here:

http://web.archive.org/web/20080212232542/http://www.robherbst.com/blog/2006/08/21/c-weakreference-example/

Andrew Rollings
FYI, the link above no longer works :(
daub815
Updated to refer to the wayback machine copy instead.
Andrew Rollings
+2  A: 

Here is the full implementation sample of WeakReference

ClassA objA = new ClassA();
WeakReference wr = new WeakReference(objA);
// do stuff 
GC.Collect();
ClassA objA2;
if (wr.IsAlive)
    objA2 = wr.Target as ClassA; 
else
    objA2 = new ClassA(); // create it directly if required

WeakReference is in the System namespace hence no need to include any special assembly for it.

Binoj Antony