Collection Initializers with Automatic Properties
Is there a way to use a collection initializer when also using automatic properties?
/开发者_JAVA技巧/ 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>()); }
}
// 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.
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";
精彩评论