How can I define the class so that it could be initialized similarly like List<T>:
List<int> list = new List<int>(){ //this part };
e.g., this scenario:
Class aClass = new Class(){ new Student(), new Student()//... };
Typically, to allow collection-initializer syntax directly on Class, it would implement a collection-interface such as ICollection<Student>or similar (say by inheriting from Collection<Student>).
But technically speaking, it only needs to implement the non-generic IEnumerable interface and have a compatible Add method.
So this would be good enough:
using System.Collections;
public class Class : IEnumerable
{
// This method needn't implement any collection-interface method.
public void Add(Student student) { ... }
IEnumerator IEnumerable.GetEnumerator() { ... }
}
Usage:
Class aClass = new Class { new Student(), new Student() };
As you might expect, the code generated by the compiler will be similar to:
Class temp = new Class();
temp.Add(new Student());
temp.Add(new Student());
Class aClass = temp;
For more information, see section "7.6.10.3 Collection initializers" of the language specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With