Today I was surprised to find that in C# I can do:
List<int> a = new List<int> { 1, 2, 3 };
Why can I do this? What constructor is called? How can I do this with my own classes? I know that this is the way to initialize arrays but arrays are language items and Lists are simple objects …
This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:
It implements
IEnumerable(preferablyIEnumerable<T>)It has a method named
Add(...)What happens is the default constructor is called, and then
Add(...)is called for each member of the initializer.Thus, these two blocks are roughly identical:
And
You can call an alternate constructor if you want, for example to prevent over-sizing the
List<T>during growing, etc:Note that the
Add()method need not take a single item, for example theAdd()method forDictionary<TKey, TValue>takes two items:Is roughly identical to:
So, to add this to your own class, all you need do, as mentioned, is implement
IEnumerable(again, preferablyIEnumerable<T>) and create one or moreAdd()methods:Then you can use it just like the BCL collections do:
(For more information, see the MSDN)