Why not wrap a Lazy<T>
and then lazy load the Lazy<T>
in your Get
public class MyLazy {
private object lazy;
private object _Lock = new object();
public T Get<T>(Func<T> factory) {
if (lazy == null) {
lock (_Lock) {
if (lazy == null) {
lazy = new Lazy<T>(factory);
}
}
}
return ((Lazy<T>)lazy).Value;
}
}
Taking advantage of existing features that have been tried and tested instead of trying to roll your own.
Running with the suggestion proposed by t3chb0t, a factory could look something like
public static class LazyFactory {
static object syncLock = new object();
static Dictionary<Delegate, object> cache = new Dictionary<Delegate, object>();
public static T GetOrCreate<T>(Func<T> valueFactory) {
object lazy;
if (!cache.TryGetValue(valueFactory, out lazy)) {
lock (syncLock) {
if (!cache.TryGetValue(valueFactory, out lazy)) {
lazy = new Lazy<T>(valueFactory);
cache[valueFactory] = lazy;
}
}
}
return ((Lazy<T>)lazy).Value;
}
}
Now in the end, the more I think about this endeavor the more I wonder if this is even worth the hassle because after all the wrapping of the Lazy<T>
you still end up calling the Value
immediately after, which in my opinion defeats the the purpose of having the Lazy<T>
to begin with.