I did it like this:
public static class LazyCachableGetter { private static ConditionalWeakTable<object, IDictionary<string, object>> Instances = new ConditionalWeakTable<object, IDictionary<string, object>>(); public static R LazyValue<T, R>(this T obj, Func<R> factory, [CallerMemberName] string prop = "") { R result = default(R); if (!ReferenceEquals(obj, null)) { if (!Instances.TryGetValue(obj, out var cache)) { cache = new ConcurrentDictionary<string, object>(); Instances.Add(obj, cache); } if (!cache.TryGetValue(prop, out var cached)) { cache[prop] = (result = factory()); } else { result = (R)cached; } } return result; } }
and later you can use it as
public virtual bool SomeProperty => this.LazyValue(() => { return true; });
Alexander Zuban Oct 24 '18 at 16:05 2018-10-24 16:05
source share