I have an object with List<>
s exposed by properties. I generally initialize my lists within the property getter as follows:
public class Foo
{
private List<bar> _barList;
public List<bar>
{
get
{
if(_barList == null)
{
_barList = new List<Bar>()
}
return _barList;
}
set
{
_barList = value;
}
}
public Foo()
{
}
}
However, my colleagues generally prefer initializing the list in the class constructor as follows:
public class Foo
{
public List<bar> BarList { get; set; }
public Foo()
{
BarList = new List<Bar>();
}
}
Both cases prevent BarList
from being accessed before it is initialized. The second seems more neat due to the use of autoproperties. The first seems like a better option though, since the list is only initialized when it is first used. Are there any other considerations I should take into account? Is there a best practice for this?