RSS

Generic WeakReference Class

20 Apr

The WeakReference class is used to get a reference to an object X in such a way that the garbage collector (GC) can still reclaim it. Holding a ‘normal’, strong reference to object X would stop the GC from collecting it.

The .Net BCL currently only contains a non-generic class for this functionality, so I wrote a simple generic version…

namespace System
{
  public class WeakReference<T> : WeakReference
  {
    public new T Object
    {
      get
      {
        return (T)base.Target;
      }
      set
      {
        base.Target = value;
      }
    }
    public WeakReference(T target)
      : base(target)
    {
    }
    public WeakReference(T target, bool trackResurrection)
      : base(target, trackResurrection)
    {
    }
    protected WeakReference(SerializationInfo info, StreamingContext context)
      : base(info, context)
    {
    }
  }
}

And here’s how you can use it…

public class Dog : IDisposable
{
  public readonly string Name;

  public Dog(string name)
  {
    Name = name;
  }

  // IDisposable routines left out for brevity
}

public class Consumer
{
  public void DoSomething()
  {
    using (var myDog = new Dog("Dioji"))
    {
      var weakReference = new WeakReference<Dog>(myDog);

      Console.WriteLine("My dog is called '{0}'.", weakReference.Object.Name);
    }
  }
}

I’ll demonstrate why this can be really useful in my next post on the “Enhancing the Aggregate Pattern in Domain Driven Design with Weak References“.

Advertisements
 
Leave a comment

Posted by on April 20, 2010 in C#

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: