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'm creating a Data class:
Data data = new Data { List = { "1", "2", "3", "4" } };
The list was filled with strings "1", "2", "3", "4" even if it had no set
.
Why is this happening?
Your object initializer (with collection initializer for List
)
Data data = new Data { List = { "1", "2", "3", "4" } };
gets turned 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 it this way it should be clear why you are, in fact, adding to string1
and not to string2
: tmp.List
returns string1
. You never assign to the property, you just initialize the collection that is returned. Thus you should look at the getter here, not the setter.
However, Tim is absolutely correct in that a property defined in that way doesn't make any sense. This violates the principle of least surprise and to users of that class it's not at all apparent what happens with the setter there. Just don't do such things.