views:

405

answers:

3

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};
+3  A: 

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};
}
RossFabricant
+1, you may want to add that it must take a parameter of the type in the collection.
JaredPar
Actually, that's not true. It would be weird, but your Add method does not need to take type T. It could be: public void Add(string t, char c){}and you could call MyList<int> a = new MyList<int>{{"A", 'c'}, {"B", 'd'}};
RossFabricant
+1  A: 

Implementing ICollection on MyList will let the initalizer syntax work

class MyList : ICollection

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()
    {
    }


}
JoshBerke
A: 
ICollection<T> is also good.