@chibacity is published (and subsequently) deleted [and later restored: P] an alternative using an abstract base class. Although it may not be ideal in terms of code distribution, it does provide excellent encapsulation by removing a lot of code cloning for a cleaner and more concise class. For example, you might consider combining methods to achieve both goals:
public class ClassB { } public abstract class BaseA { private Lazy<ClassB> _b = new Lazy<ClassB>(() => new ClassB()); public virtual ClassB B { get { return _b.Value; } } } public class ClassA : BaseA { public override ClassB B { get { return base.B; } } }
At first glance, it seems that this is a longer wind, but if you think that ClassA, which is the class in which you will work and with which, it means that all your links go through the same property - there is no extraneous an unnecessary field causing potential confusion, there is no going around the property for the _b link directly, and there is no need to tell your colleague who should use ... there is only one.
Not to say that this is the right way to do this or that, it is a template that should or should not be respected, I just point out the advantages of what @chibacity suggested, which might otherwise go unnoticed.
It would be nice if you had implicit lazy loaded properties without reference to B.Value ... for example:
[Lazy] public ClassB B { get; }
or for objects without constructors without parameters
[Lazy(() => new ClassB("Hello", "World"))] public ClassB B { get; }
or maybe like @chibacity suggested in the comment
public ClassB B { lazyget; }
or
public ClassB B { lazyget : new ClassB(); }
Alas, I do not think that any of them are currently available in any form ...
Benalabaster
source share