Checking lazy loaded properties have been instantiated

Posted by PaulG on Stack Overflow See other posts from Stack Overflow or by PaulG
Published on 2010-05-14T09:23:45Z Indexed on 2010/05/14 9:44 UTC
Read the original article Hit count: 249

Filed under:
|

In a class which has a lazy loaded property, such as:

private Collection<int> someInts;

public Collection<int> SomeInts
{
    get
    {
        if (this.someInts == null) this.someInts = new Collection<int>();
        return this.someInts;
    }
}

Is it worth also having a property such as:

public bool SomeIntsExist
{
    get { return (this.someInts != null && this.someInts.Count > 0); }
}

And then using that property.. eg:

if (thatClass.SomeIntsExist)
{
    // do something with thatClass.SomeInts collection
}

or is this premature optimisation. Its certainly easier to roll with something like below, but it will instantiate the collection needlessly:

if (thatClass.SomeInts.Count > 0)
{
    // do something with thatClass.SomeInts collection
}

Is the compiler smart enough to figure things like this out? Is there a better way?

© Stack Overflow or respective owner

Related posts about c#

Related posts about lazy-loading