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 case of List2 it is ok, using "=" we set property. But in List1 case it looks like we set property, but actually, we suppose to set it somewhere before, and here we only set values. And it very similar to array initializing:
string[] arr = { "val1", "val2" }
Why C# uses this confusing syntax here?
Edit: I guess I confused many viewers with C# 6.0 syntax, but it's not the point. Let's use old good C# 3.0 and .net 2.0. And lets add more fun too this and add some values ("1" and "2") to the list from start, 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 list { "1", "2", "asdf", "qwer" }, which is even more confusing. I can expect this the less.