Why do C# collection initializers work this way?

后端 未结 3 1484
无人及你
无人及你 2020-11-28 21:51

I was looking at C# collection initializers and found the implementation to be very pragmatic but also very unlike anything else in C#

I am able to create code like

3条回答
  •  情书的邮戳
    2020-11-28 22:20

    I thought about this too, and the answer which satisfies me the most is that ICollection has many methods other than Add, such as: Clear, Contains, CopyTo, and Remove. Removing elements or clearing has nothing to do with being able to support the object initializer syntax, all you need is an Add().

    If the framework was designed granularly enough, and there was an ICollectionAdd interface, then it would've had a "perfect" design. But I honestly don't think that would have added much value, having one method per interface. IEnumerable + Add seems like a hackish approach, but when you think about it, it's a better alternative.

    EDIT: This is not the only time C# has approached a problem with this type of solution. Since .NET 1.1, foreach uses duck typing to enumerate a collection, all your class needs to implement is GetEnumerator, MoveNext and Current. Kirill Osenkov has a post which asks your question as well.

提交回复
热议问题