Why do C# collection initializers work this way?

后端 未结 3 1472
无人及你
无人及你 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:36

    (I know I am 3 years late on this, but I was not satisfied with the existing answers.)

    why, in order for this syntax to compile, does the compiler not require that the type implement ICollection?

    I'll reverse your question: What use would it be if the compiler had requirements that are not really needed?

    Non-ICollection classes too can benefit from the collection initializer syntax. Consider classes that allow adding data into them, without allowing access to previously added data.

    Personally, I like to use the new Data { { ..., ... }, ... } syntax to add a light, DSL-like look to the code of my unit tests.

    Actually, I'd rather weaken the requirement, so that I can use the nice-looking syntax without even having to bother implementing IEnumerable. Collection initializers are pure syntactic sugar to Add(), they shouldn't require anything else.

提交回复
热议问题