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()//... };
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Typically, to allow collection-initializer syntax directly on
Class, it would implement a collection-interface such asICollection<Student>or similar (say by inheriting fromCollection<Student>).But technically speaking, it only needs to implement the non-generic
IEnumerableinterface and have a compatibleAddmethod.So this would be good enough:
Usage:
As you might expect, the code generated by the compiler will be similar to:
For more information, see section “7.6.10.3 Collection initializers” of the language specification.