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
(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.