Friday, March 4, 2011

Are there Weak References in .NET?

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.

From stackoverflow
  • Yes, there's a generic weak reference class.

    MSDN > Weak Reference

  • Can you create weak references in .NET?

    Yes:

    WeakReference r = new WeakReference(obj);
    

    Uses System.WeakReference.

  • 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/

    daub815 : FYI, the link above no longer works :(
    Andrew Rollings : Updated to refer to the wayback machine copy instead.
  • 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.

0 comments:

Post a Comment