Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initialization similar to List<> syntax

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()//... };
like image 933
Miro Avatar asked Jul 09 '26 18:07

Miro


1 Answers

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.

like image 168
Ani Avatar answered Jul 12 '26 07:07

Ani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!