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):
private readonly List<int> _numbers = new List<int>();
public List<int> Numbers { get { return _numbers; } }
or if I want to defer construction until the first access:
private List<int> _numbers;
public List<int> Numbers {
get { return _numbers ?? (_numbers = new List<int>()); }
}
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