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(); }
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(); }
source share