Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing a "LazyProperty" class - is this a good idea?
    text
    copied!<p>I often find myself writing a property that is evaluated lazily. Something like:</p> <pre><code>if (backingField == null) backingField = SomeOperation(); return backingField; </code></pre> <p>It is not much code, but it does get repeated a lot if you have a lot of properties.</p> <p>I am thinking about defining a class called LazyProperty:</p> <pre><code>public class LazyProperty&lt;T&gt; { private readonly Func&lt;T&gt; getter; public LazyProperty(Func&lt;T&gt; getter) { this.getter = getter; } private bool loaded = false; private T propertyValue; public T Value { get { if (!loaded) { propertyValue = getter(); loaded = true; } return propertyValue; } } public static implicit operator T(LazyProperty&lt;T&gt; rhs) { return rhs.Value; } } </code></pre> <p>This would enable me to initialize a field like this:</p> <pre><code>first = new LazyProperty&lt;HeavyObject&gt;(() =&gt; new HeavyObject { MyProperty = Value }); </code></pre> <p>And then the body of the property could be reduced to:</p> <pre><code>public HeavyObject First { get { return first; } } </code></pre> <p>This would be used by most of the company, since it would go into a common class library shared by most of our products.</p> <p>I cannot decide whether this is a good idea or not. I think the solutions has some pros, like: </p> <ul><li>Less code</li> <li>Prettier code</li> </ul> <p>On the downside, it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class. </p> <p>What do you think ? Is this a good idea or should I abandon it ? Also, is the implicit operator a good idea, or would you prefer to use the Value property explicitly if you should be using this class ? </p> <p>Opinions and suggestions are welcomed :-)</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