Search code examples
c#copycloneinterface-implementation

Implementing ICollection.CopyTo in C#: deep or shallow copy?


I'm writing a custom class which implements IDictionary, and I'm not sure what to do about CopyTo. Should each element just be copied to the target array (shallow copy), or should I make a copy/clone of each element then place it in the target array (deep copy)?


Solution

  • The implementation is not defined by the contract, however all the generic collections appear to do a shallow copy (see http://referencesource.microsoft.com/#q=List.CopyTo). It makes sense, as there is no defined way to deep copy any object, which would be part of the CopyTo implementation.

    It depends on your scenario, if you do not intend to use this method at all, consider not implementing it and throwing a NotSupportedException. If others will use your collection, implement a shallow copy to align with the standard .NET library. If you need a deep copy method, add it as a separate method, (potentially by implementing ICloneable).