Miro
Miro

Reputation: 1806

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()//... };

Upvotes: 3

Views: 219

Answers (3)

Ani
Ani

Reputation: 113402

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.

Upvotes: 6

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

I didn't see anyone suggesting generics implementation so here it is.

    class Class<T>  : IEnumerable
{
    private List<T> list;
    public Class()
    {
        list = new List<T>();
    }

    public void Add(T d)
    {
        list.Add(d);
    }

    public IEnumerator GetEnumerator()
    {
        return list.GetEnumerator();
    }
}

and use:

Class<int> s = new Class<int>() {1,2,3,4};

Upvotes: 0

Oded
Oded

Reputation: 498914

If you define MyClass as a collection of students:

public class MyClass : List<Student>
{
}

var aClass = new MyClass{  new Student(), new Student()//... }

Alternatively, if your class contains a public collection of Student:

public class MyClass
{
  public List<Student> Students { get; set;}
}

var aClass = new MyClass{ Students = new List<Student>
                                     { new Student(), new Student()//... }}

Which one you select really depends on how you model a class.

Upvotes: 1

Related Questions