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?
In addition to usrs answer, there is a another answer, using C# 6.0, on this question.
One of the new features is a initializer for auto-implemented properties. You'd write:
public class Foo
{
public List<bar> BarList { get; set; } = new List<bar>();
}
Also, have a look at the new primary constructors, found a programmers.stackexchange article.
This initializer will be called on object-initialization. In matters of memory consumption/performance, it should be equal to initializing the property in the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With