Suppose we have a very simple class:
class ObjectList { public List<string> List1 { get; } = new List<string>(); public List<string> List2 { get; set; } }
and we want to make an instance of this class:
ObjectList objectList = new ObjectList { List1 = { "asdf", "qwer" }, List2 = new List<string> { "zxcv", "1234" } };
So, in the case of List2, this is normal, using "=" we set the property. But in the case of List1, it looks like we are setting a property, but in fact we are planning to set it somewhere earlier, and here we are setting only the values. And this is very similar to array initialization:
string[] arr = { "val1", "val2" }
Why is C # using this confusing syntax here?
Edit: I guess I confused many viewers with C # 6.0 syntax, but that's not the point. Let me use the good old C # 3.0 and .net 2.0. And add even more fun and add some values ("1" and "2") to the list from the beginning, as Jeff Mercado recommended:
class Program { static void Main(string[] args) { ObjectList objectList = new ObjectList { List1 = { "asdf", "qwer" }, }; } } class ObjectList { List<string> _List1 = new List<string>() { "1", "2" }; public List<string> List1 { get { return _List1; } } }
It shows the same weird syntax. And at the end I have a list {"1", "2", "asdf", "qwer"}, which is even more confusing. I can expect it to be less.