Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection Initializers with Automatic Properties

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>();
like image 917
kenwarner Avatar asked Jul 13 '26 09:07

kenwarner


1 Answers

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>()); }
}
like image 69
Marc Gravell Avatar answered Jul 18 '26 02:07

Marc Gravell