Pages

Tuesday 20 April 2010

Generic WeakReference Class

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 string Name
  {
    get;
    private set;
  }

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

No comments:

Post a Comment