Be aware of deep copy with Collection<T>(IList<T>)
Usually when I need to create a copy of some primitive type collection based on List<T> usually I use overload constructor of List class such as List<T>(IEnumerable<T>). It basically creates a new List<T> collection and populates the items based on IEnumerable<T> input parameter. Copied version is isolated from the original one which means changes made in copied version will not effect the original one.
Recently I had the same task but instead of List<T> I had to use Collection<T> and it was required to make a deep copy of that collection. I was expecting that constructor Collection<T>(IList<T>) will do the same what List<T> does and will return me a new instance of Collection<T> object isolated from the original one.
For my big surprise it didn’t. It actually wraps the original collection. So, those two collections are coupled to each other. As soon as you make a changes in the “copied” version the original collection will be effected as well.
This is a small example which illustrates it:
So, be careful when you need to make a Deep Copy of collection.
Technorati tags:
.Net,
C#