Is there a way to use a collection initializer when also using automatic properties?
// Uses collection initializer but not automatic properties
private List<int> _numbers = new List<int>();
public List<int> Numbers
{
get { return _numbers; }
set { _numbers = value; }
}
// Uses automatic properties but not collection initializer
public List<int> Numbers { get; set; }
// Is there some way to do something like this??
public List<int> Numbers { get; set; } = new List<int>();
No, basically. You would have to initialize the collection in the constructor. To be honest, a settable collection is rarely a good idea anyway; I would actually use just (changing your first version, removing the
set):or if I want to defer construction until the first access: