c# – How to implement initialization when declaring your own C # collection

Question:

Is it possible to initialize your own collection when declaring it, as in the built-in List<T> , that is, like this:

MyCollection<int> mcl = new MyCollection<int>() { 1, 2, 3, 4 };

Answer:

In order for the initialization syntax to work with your collection, the following conditions must be met: the collection class must implement the IEnumerable interface (or IEnumerable<T> , which inherits from IEnumerable ), and define an available Add method (by the way, it can be extension method), which will be called for each item in the initialization list.

MyCollection mcl = new MyCollection() {1,2,3,4}; code MyCollection mcl = new MyCollection() {1,2,3,4}; will compile to this:

MyCollection tmp = new MyCollection(); // реальное имя будет недоступно
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
tmp.Add(4);
MyCollection mcl = tmp;

Proof

The IEnumerable interface will not be used, it is only needed so that a randomly available Add method does not lead to the availability of an initialization syntax that makes sense only for collections.


Why use a temporary variable? The fact is that the initialization list code may well use mcl directly or indirectly (for example, for the case if mcl is a class field or a previously declared variable), and it is clear that the code should not have access to the undeveloped right side of the assignment.

Scroll to Top