Tuesday, November 29, 2005 6:38 PM
Mickey Williams
FAQ: How do I make a working copy of a generic collection?
I've been asked this question a few times in a variety of ways. Essentially:
What's the best way to create a working copy of a collection that I can use without mutating the original collection?
There is a ctor overload for collections such as List<T> that accepts an existing collection as a parameter. Given a variable (foos) that is a List<Foo>:
List<Foo> workingNames = new List<Foo>(foos);
Two background notes:
- This is one area where I feel that Eiffel's creation metaphor is superior to C++ and C#. Rather than exposing three constructors with the same name, in Eiffel I would have a creation feature named create_shallow_clone(...).
- As a side note, the ICloneable interface in the Framework is broken, as it enforces no semantics WRT deep versus shallow copying. I'll save that for a posting tomorrow.