Implementing a collection initializer for my List wrapper in C #

I created a class that wraps a List:

class Wrapper { private List<int> _list } 

I would like to be able to initialize a new Wrapper object as follows:

 new Wrapper() {1, 2, 3}; 

It is supposed to initialize Wrapper _list to a list containing {1, 2, 3}.

What do I need to add to the class code to enable functionality?

+4
source share
2 answers

You need two things:

  • You need to implement IEnumerable (although its behavior does not matter for the collection initializer itself). You do not need to implement a generic version, but you would usually like to.
  • You need an Add method that takes the type of an element as a parameter ( int in this case)

So then the compiler will convert this:

 Wrapper x = new Wrapper() {1, 2, 3}; 

In it:

 Wrapper tmp = new Wrapper(); tmp.Add(1); tmp.Add(2); tmp.Add(3); Wrapper wrapper = tmp; 

The simplest approach would almost certainly have been to delegate your list:

 class Wrapper : IEnumerable<int> { private readonly List<int> _list = new List<int>(); public IEnumerator<int> GetEnumerator() { return _list.GetEnumerator(); } // Explicit implementation of non-generic interface IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(int item) { _list.Add(item); } } 

If you want to make your wrapper a little more efficient for repetition, you can change the GetEnumerator methods to include a public one that returns a List<T>.Enumerator :

 // Public method returning a mutable struct for efficiency public List<T>.Enumerator GetEnumerator() { return _list.GetEnumerator(); } // Explicit implementation of non-generic interface IEnumerator<int> IEnumerable<int>.GetEnumerator() { return GetEnumerator(); } // Explicit implementation of non-generic interface IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } 
+5
source
 class ListWrapper :IEnumerable<int> { private List<int> _list = new List<int>(); public void Add(int i) { _list.Add(i); } public IEnumerator<int> GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); } } 
+2
source

All Articles