I’ve created a class which wraps a List:
class Wrapper
{
private List<int> _list
}
I would like to be able to initialize a new Wrapper object like this:
new Wrapper() {1, 2, 3};
That’s supposed to initialize the Wrapper’s _list to a list containing {1, 2, 3}.
What do I need to add to the class code in order to enable the functionality?
You need two things:
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.Addmethod accepting the element type as a parameter (intin this case)So the compiler will then transform this:
Into this:
The simplest approach would almost certainly be to delegate to your list:
If you want to make your wrapper slightly more efficient to iterate over, you could change the
GetEnumeratormethods to include a public one returningList<T>.Enumerator: