Generic WeakReference

I always felt that I wanted to use the WeakReference class a lot like the Nullable<T> class.


internal class WrappedWeakReference<T> : WeakReference
 {
 public WrappedWeakReference(T target)
 : base(target)
 {
 }

 public new T Target
 {
 get { return (T) base.Target; }
 set { base.Target = value; }
 }

 public static implicit operator WrappedWeakReference<T>(T item)
 {
 return new WrappedWeakReference<T>(item);
 }
 }

This allows you to write things like:

 private WrappedWeakReference<MyObject> weakMyObject;

 public void Foo()
 {
 weakMyObject = new MyObject();
 }

 public void Bar()
 {
 weakMyObject.Target.SomeProperty....etc
 }
}

I think its nice idea.

However never did actually use this, I implemented the solution in a different manner where I did not need a weakreference, so this never got tested. I am not sure if it would work.

Leave a Reply