Friday, April 15, 2011

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};
From stackoverflow
  • 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};
    }
    
    JaredPar : +1, you may want to add that it must take a parameter of the type in the collection.
    RossFabricant : 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 a = new MyList{{"A", 'c'}, {"B", 'd'}};
  • 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()
        {
        }
    
    
    }
    
  • ICollection<T> is also good.
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.