How does an inline list override a property without customization?

I have an Item class that has a public NoSetter member that does not contain setter. The object explicitly indicates get, which retrieves the private Listedly List object.

class Item { private readonly List<string> emptyString; public Item() { this.emptyString = new List<string>(); } public List<string> NoSetter { get { return this.emptyString; } } } 

When you create this object, you cannot set NoSetter to the list, the compiler does not work when you try.

 List<string> goldenString = new List<string>(); goldenString.Add("Nope"); Item item = new Item() { NoSetter = goldenString // or NoSetter = new List<string>(); }; 

However, if you create an inline list, you can install NoSetter.

 Item item = new Item() { NoSetter = { "But this still works" } }; // Outputs: "But this still works" Console.WriteLine(item.NoSetter.First<string>()); 

I expect the NoSetter.Get method to return a readonly emptyString, but instead returns an inline NoSetter object. What causes this in .net? Expected?

+5
source share
1 answer

The second code snippet does not set a new List<string> , it just adds a value to it.

 Item item = new Item() { NoSetter = { "But this still works" } }; 

It is equivalent to:

 Item item = new Item(); item.NoSetter.Add("But this still works"); 

The syntax {...} when applied to a collection is known as a Collection Initializer . Quote from the documentation (my selection):

Collection initializers allow you to specify one or more element initializers when initializing a collection class that implements IEnumerable. Element initializers can be a simple value, expression, or object initializer. Using the collection initializer, you do not need to specify several calls to the add class method in the source code; the compiler adds calls.

+11
source

All Articles