Svish
Svish

Reputation: 157981

C#: List add object initializer

Lets say I have this class:

class MyList<T>
{

}

What must I do to that class, to make the following possible:

var list = new MyList<int> {1, 2, 3, 4};

Upvotes: 0

Views: 1770

Answers (3)

JoshBerke
JoshBerke

Reputation: 67068

Implementing ICollection on MyList will let the initalizer syntax work

class MyList<T> : ICollection<T>
{
}

Although the bare minimum would be:

public class myList<T> : IEnumerable<T>
{
    public void Add(T val)
    {
    }

    public IEnumerator<T> GetEnumerator()
    {
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
    }
}

Upvotes: 1

Reputation:

ICollection<T> is also good.

Upvotes: 0

RossFabricant
RossFabricant

Reputation: 12492

Have an Add method and implement IEnumerable.

class MyList<T> : IEnumerable
{
  public void Add(T t)
  {

  }

  public IEnumerator GetEnumerator()
  {
    //...
  }
}

public void T()
{
  MyList<int> a = new MyList<int>{1,2,3};
}

Upvotes: 3

Related Questions