a DotNetStyling - .Net World by Armen Ayvazyan : Be aware of deep copy with Collection<T>(IList<T>)
Welcome to DotNetStyling Sign in | Join | Help
Add to Technorati Favorites Add to Google Reader or Homepage Add to My AOL Subscribe in FeedLounge Subscribe in Bloglines Add to Excite MIX Add to flurry Add to Pageflakes Subscribe in NewsGator Online


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:

image

image

So, be careful when you need to make a Deep Copy of collection.

Technorati tags: ,
Posted: 19. března 2009 9:36 by admin

Comments

New Comments to this post are disabled