title: Methods for Lazy Initialization with properties
body: <p>I'm currently altering a widely used class to move as much of the expensive initialization from the class constructor into Lazy Initialized properties. Below is an example (in c#):</p>
  
  <p>Before:</p>
  
  <pre><code>public class ClassA
  {
      public readonly ClassB B;
  
      public void ClassA()
      {
          B = new ClassB();
      }
  }
  </code></pre>
  
  <p>After:</p>
  
  <pre><code>public class ClassA
  {
      private ClassB _b;
  
      public ClassB B
      {
          get
          {
              if (_b == null)
              {
                  _b = new ClassB();
              }
  
              return _b;
          }
      }
  }
  </code></pre>
  
  <p>There are a fair few more of these properties in the class I'm altering, and some are not used in certain contexts (hence the Laziness), but if they are used they're likely to be called repeatedly.</p>
  
  <p>Unfortunately, the properties are often also used inside the class. This means there is a potential for the private variable (_b) to be used directly by a method without it being initialized.</p>
  
  <p>Is there a way to make only the public property (B) available inside the class, or even an alternative method with the same initialized-when-needed?</p>
  
  <p>This is reposted from Programmers (not subjective enough apparently):
  <a href="https://softwareengineering.stackexchange.com/questions/34270/best-methods-for-lazy-initialization-with-properties">https://softwareengineering.stackexchange.com/questions/34270/best-methods-for-lazy-initialization-with-properties</a></p>