I've been reading about WeakPointer
and WeakPointer<T>
today, and it looks very useful. Rather than just using it as-is though, I decided to write a wrapper around it that covers a common usage case for me.
Code as follows:
public class Temporary<T> where T : class
{
Func<T> generator = null;
WeakReference<T> reference = null;
public T Value
{
get
{
return GetValue();
}
}
public Temporary(T value)
: this(value, null)
{ }
public Temporary(Func<T> generator)
: this(null, generator)
{ }
public Temporary(T value, Func<T> generator)
{
reference = new WeakReference<T>(value);
this.generator = generator;
}
public T GetValue()
{
if (reference == null)
return null;
T res;
if (!reference.TryGetTarget(out res) && generator != null)
{
res = generator();
reference.SetTarget(res);
}
return res;
}
}
I've tested this against my use-case and it works as I expect - the garbage collector cleans out items with no active references, and they are re-instantiated at need.
I'm looking for critiques of the implementation and suggestions for improvements/additions.