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)?
Asked
Active
Viewed 1,409 times
4

Eric Dand
- 1,106
- 13
- 37
-
1Which `CopyTo` are you referring to? `IEnumerable` has no `CopyTo` method. – John Saunders Jun 09 '15 at 02:29
-
@JohnSaunders `ICollection` does though, and since OP is implementing an `IDictionary`, I suspect they need to implement `ICollection.CopyTo`. – Asad Saeeduddin Jun 09 '15 at 02:30
-
I suspect the same, but we should demand precision, since computers do precisely what we tell them to do. – John Saunders Jun 09 '15 at 02:31
-
Ahhh, whoops! Sorry about that. I'll edit the question... – Eric Dand Jun 09 '15 at 02:31
-
See https://msdn.microsoft.com/en-us/library/system.collections.dictionarybase.copyto.aspx. Better still, see https://msdn.microsoft.com/en-us/library/cc645053.aspx – John Saunders Jun 09 '15 at 02:31
-
Also, are you really implementing `IDictionary` or the generic `IDictionary
`? – Asad Saeeduddin Jun 09 '15 at 02:33 -
@Asad Neither, actually: I'm implementing `IDictionary
, MyClass>`. I figured the question applied regardless, though, so I left that detail out. – Eric Dand Jun 09 '15 at 02:35 -
1Always shallow for `IDictionary`. Since the elements are of type `object` you have no way of knowing how to do a deep copy. – Enigmativity Jun 09 '15 at 02:36
1 Answers
5
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
).

Bas
- 26,772
- 8
- 53
- 86