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?
Even lazy initialization of a property sounds like premature optimization. There are only very few cases I can think of where delaying the creation of an empty collection helps to solve a problem (assuming your example is not oversimplified).
But when you have to delay the collection initialization then you probably should (or even have to) optimize the
Existsmethod, too, because lazy initialization is a critical requirement.