Scott’s lazy loader
Scott Wisniewski posted a lazy loader implementation on his blog. He coded it blind, without the help of a compiler that could do C# generics. I went back through and made it legal C# code. I also did a little refactoring.
- The ILazyLoader is now nested in the LazyLoad<T> class, which means it doesn’t need its own type parameter.
- The getter has only one return.
- A DefaultLoad derives from LazyLoad, and adds the ‘new()’ constraint to T.
The code is now legal C#, but I haven’t verified that it actually works yet.
public class LazyLoad<T>
{
public interface ILazyLoader
{
T CalculateValue();
}
private T value_;
private bool didFetch_ = false;
private ILazyLoader lazyLoader_;
public LazyLoad(ILazyLoader lazyLoader)
{
lazyLoader_ = lazyLoader;
}
public T Value
{
get
{
if (!didFetch_)
{
didFetch_ = true;
value_ = lazyLoader_.CalculateValue();
}
return value_;
}
}
}
public class DefaultLazyLoad<T> : LazyLoad<T>
where T : new()
{
public class DefaultConstructLazyLoader : ILazyLoader
{
public DefaultConstructLazyLoader() { }
public T CalculateValue()
{
return new T();
}
}
public DefaultLazyLoad() : base(new DefaultConstructLazyLoader()) { }
}