Methods for Lazy Initialization with properties

Posted by Stuart Pegg on Stack Overflow See other posts from Stack Overflow or by Stuart Pegg
Published on 2011-01-06T15:57:23Z Indexed on 2011/01/06 17:54 UTC
Read the original article Hit count: 387

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#):

Before:

public class ClassA
{
    public readonly ClassB B;

    public void ClassA()
    {
        B = new ClassB();
    }
}

After:

public class ClassA
{
    private ClassB _b;

    public ClassB B
    {
        get
        {
            if (_b == null)
            {
                _b = new ClassB();
            }

            return _b;
        }
    }
}

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.

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.

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?

This is reposted from Programmers (not subjective enough apparently): http://programmers.stackexchange.com/questions/34270/best-methods-for-lazy-initialization-with-properties

© Stack Overflow or respective owner

Related posts about c#

Related posts about c#-3.0