You need two things:
- You need to implement
IEnumerable
(although its behaviour is unimportant for the sake of the collection initializer itself). You don't have to implement the generic version, but you'd normally want to.
- You need an
Add
method accepting the element type as a parameter (int
in this case)
So the compiler will then transform this:
Wrapper x = new Wrapper() {1, 2, 3};
Into this:
Wrapper tmp = new Wrapper();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
Wrapper wrapper = tmp;
The simplest approach would almost certainly be to delegate to 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 slightly more efficient to iterate over, you could change the GetEnumerator
methods to include a public one returning 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();
}