I have a public property (AllCustomers), which is backed by a private property for lazy loading.
I understand that the public property should be IEnumerable ("program to interfaces, not implementations").
However, I can see two ways to build the private property.
First option, with private List-
private List<Customer> _AllCustomers;
public IEnumerable<Customer> AllCustomers
{
get
{
if (_AllCustomers == null)
{
_AllCustomers = DAL.GetAllCustomers().ToList();
}
return _AllCustomers;
}
}
Second option, with private IEnumerable-
private IEnumerable<Customer> _AllCustomers;
public IEnumerable<Customer> AllCustomers
{
get
{
if (_AllCustomers == null)
{
_AllCustomers = DAL.GetAllCustomers();
}
return _AllCustomers;
}
}
I think the first option appears more correct, as it will hit the database once and store the results, whereas the second will result in multiple database hits.
My questions are-
- Am I correct in my analysis?
- What are the implications of the different approaches?
- Is there any time the second option would be preferred?
- Are there better, more idiomatic ways to express the second option?