3

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>();
kenwarner
  • 28,650
  • 28
  • 130
  • 173
  • 1
    possible duplicate of [automatic property with default value](http://stackoverflow.com/questions/4691888/automatic-property-with-default-value) – AakashM Apr 21 '11 at 20:11

3 Answers3

4

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>()); }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

// Is there some way to do something like this??

public List<int> Numbers { get; set; } = new List<int>();

No. You have to initialize in an explicitly-defined constructor, there are no field-initialization tricks to apply here.

Also, this has nothing to do with collection intializers. You also can't initialize

public object Foo { get; set; }

outside of a constructor.

jason
  • 236,483
  • 35
  • 423
  • 525
0

apparently your voice was heard. I just stumbled across this being used for the first time in a new codebase.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

"In C# 6 and later, you can initialize auto-implemented properties similarly to fields:"

public string FirstName { get; set; } = "Jane";  
m1m1k
  • 1,375
  • 13
  • 14