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()//... };
1
  • Does your class inherit from IList? Commented Dec 26, 2011 at 10:52

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)?
ICollection<T> does have an Add method, although the method that the compiler binds needn't come from that interface (as the example demonstrates). Whether to implement IList<T> or not comes down to whether the collection must support fast access by index.
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.

Comments

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};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.