3

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()//... };
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Miro
  • 1,778
  • 6
  • 24
  • 42

3 Answers3

6

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • But nor ICollection and nor IEnumarable have void Add() method, only IList has it.Does it mean that I need to implement IList (is that better practice, although your example works well)? – Miro Dec 26 '11 at 11:20
  • `ICollection` does have an [`Add`](http://msdn.microsoft.com/en-us/library/63ywd54z.aspx) method, although the method that the compiler binds needn't come from that interface (as the example demonstrates). Whether to implement `IList` or not comes down to whether the collection must support fast access by index. – Ani Dec 26 '11 at 11:22
1

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

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};
Pencho Ilchev
  • 3,201
  • 18
  • 21