Unusual collection initializer syntax

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.

+5
source share
2 answers

The answer was provided by Eric Lippert in his answer to Why is the Add method necessary for {} initialization?

The design goal, motivated by typical usage scenarios for collection initializers, was to initialize existing collection types in expression syntax so that collection initializers can be embedded into query understanding or converted into expression trees.

Each other scenario was a lower priority; a function exists in general because it helps make LINQ work .

It seems that even when this syntax makes more sense when creating readonly collections, it has been added one way or another so that they can deliver LINQ in a timely manner.

+2
source

Why is C # using this confusing syntax here?

You are right that it is a little strange, but it is because you mix 2 principles. As several comments have already been noted, the syntax of { item1, items2 } converted to .Add(itemN) calls when the item to the left of = is an assembly.

Thus, strangeness is a consequence of the fact that

 List<SomeClass> list = new List<SomeClass> { item1, item2 }; SomeClass[] array = { item1, item2 }; 

handled differently.

The other part is that your sample moves the new List<SomeClass> around, but it is present in both cases.

+3
source

Source: https://habr.com/ru/post/1238892/


All Articles