Why am I allowed to change properties that are read only with object initializers?

I have this simple code:

public static void Main(String[] args) { Data data = new Data { List = { "1", "2", "3", "4" } }; foreach (var str in data.List) Console.WriteLine(str); Console.ReadLine(); } public class Data { private List<String> _List = new List<String>(); public List<String> List { get { return _List; } } public Data() { } } 

So, when I create the Data class:

 Data data = new Data { List = { "1", "2", "3", "4" } }; 

The list was filled with the lines "1", "2", "3", "4", even if it did not have set .

Why is this happening?

+7
c # properties getter-setter object-initializers collection-initializer
source share
2 answers

Object initializer (with collection initializer for List )

 Data data = new Data { List = { "1", "2", "3", "4" } }; 

turns into the following:

 var tmp = new Data(); tmp.List.Add("1"); tmp.List.Add("2"); tmp.List.Add("3"); tmp.List.Add("4"); Data data = tmp; 

Looking at this, it should be clear why you are essentially adding to string1 and not to string2 : tmp.List returns string1 . You never assign a property; you simply initialize the returned collection. So you should look at the getter here, and not at the setter.

However, Tim is absolutely right that a property defined in this way makes no sense. This violates the principle of least surprise and users of this class, but it is not clear what happens to the setter there. Just don't do such things.

+11
source share

So collection initializers work inside:

 Data data = new Data { List = { "1", "2", "3", "4" } }; 

It is basically equal

 Data _d = new Data(); _d.List.Add("1"); _d.List.Add("2"); _d.List.Add("3"); _d.List.Add("4"); Data data = _d; 

And _d.List uses string1 in the getter.

[*] Details in the C # specification 7.6.10.3 Collection initializers


Change the code as follows:

 Data data = new Data { List = new List<string>{ "1", "2", "3", "4" } }; 

And string1 will be empty, and string2 will contain four elements.

+4
source share

All Articles