Introduction
In the .NET Framework, there is no generic implementation of the System.WeakReference
class. This means that runtime casting has to be done by the developer which is error prone and repetitive work. I did this simple implementation to rid this problem. Of course, it does not help with the overhead that boxing introduces since it's still stored in an object
variable in the base class. Hopefully future releases of the framework will contain a real generic WeakReference
.
Using the Code
Just cut the code snippet below and paste it into your project to use it.
[Serializable]
public class WeakReference<T>
: WeakReference where T : class
{
public WeakReference(T target)
: base(target)
{ }
public WeakReference(T target, bool trackResurrection)
: base(target, trackResurrection)
{ }
protected WeakReference(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
public new T Target
{
get
{
return (T)base.Target;
}
set
{
base.Target = value;
}
}
}
History
- 21st December, 2007: Initial post