Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>@chibacity posted (and subsequently) deleted [and later undeleted :P] an alternative option using an abstract base class. While it may not be ideal in terms of code distribution it does provide a nice encapsulation removing a lot of code clutter making for a cleaner and more succinct ClassA. For instance, you could consider combining the techniques to achieve both goals:</p> <pre><code>public class ClassB { /* Class to be lazily instantiated */ } public abstract class BaseA { private Lazy&lt;ClassB&gt; _b = new Lazy&lt;ClassB&gt;(() =&gt; new ClassB()); public virtual ClassB B { get { return _b.Value; } } } public class ClassA : BaseA { public override ClassB B { get { return base.B; } } } </code></pre> <p>At first glance, it seems like this is more long winded, but when you consider that ClassA which is the class you would be working in and with, this now means that all your references are going through the same property - there is no extraneous unnecessary field causing potential confusion, there's no bypassing the property to reference _b directly and there's no need to tell your coworker which to use... there's only one.</p> <p>Not saying this is the right way to do this or that this is a pattern that should or shouldn't be followed, I'm just pointing out the advantages of what @chibacity suggested that may otherwise go unnoticed.</p> <p>It would be nice if you could have implicit lazy loaded properties without having to refer to B.Value... for instance:</p> <pre><code>[Lazy] public ClassB B { get; } </code></pre> <p>or for objects without parameterless constructors</p> <pre><code>[Lazy(() =&gt; new ClassB("Hello", "World"))] public ClassB B { get; } </code></pre> <p>or perhaps as @chibacity suggested in a comment</p> <pre><code>public ClassB B { lazyget; } </code></pre> <p>or</p> <pre><code>public ClassB B { lazyget : new ClassB(); } </code></pre> <p>Alas, I don't think any of these are currently available solutions in any form...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload