In C#,
Is there a way to turn an automatic property into a lazy loaded automatic property with a specified default value?
Essentially, I am trying to turn th
I did it like this:
public static class LazyCachableGetter { private static ConditionalWeakTable> Instances = new ConditionalWeakTable>(); public static R LazyValue(this T obj, Func factory, [CallerMemberName] string prop = "") { R result = default(R); if (!ReferenceEquals(obj, null)) { if (!Instances.TryGetValue(obj, out var cache)) { cache = new ConcurrentDictionary(); 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 like
public virtual bool SomeProperty => this.LazyValue(() => { return true; });