Reputation: 21176
What's the difference between:
public List<MyType> Something{ get; set; } = new List<MyType>();
and
public List<MyType> Something{
get{
return new List<MyType>();
}
//set...
}
Context:
I'm unsure of the behaviour I'm seeing in my code. A service is there on constructor, but null
on a future method call in the what I assume is the same instance of the class.
Upvotes: 2
Views: 582
Reputation: 23732
The first line:
public List<MyType> Something{ get; set; } = new List<MyType>();
will be called once when the object (that has this property) is instantiated. It is a one time creation of an instance of Something
.
The second example is an explicit implementation of the getter. Every time you access the getter of Something
it will return a new and empty list.
EDIT:
The first line is called an auto-property initializer for a detailed answer have a look at a post by Jon Skeet. This feature exists since C# 6.0
Upvotes: 8