1

Possible Duplicate:
What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Hi there! I stuck on something and I really need help :( So I have a dictionary

Dictionary<string, MyClass> dict = new Dictionary<string, MyClass>();

Where MyClass is some class with properties, methods and so on. When I try to copy this dictionary to another, for instance:

Dictionary<string, MyClass> newDict = new Dictionary<string, MyClass>(dict);

It seems that the data is copied by reference and when I try to update any MyClass object in the newDict, the data is updated and in dict. So how can I copy one dictionary to another and when I try to update the data in the copy, the data in the original stays the same?

Thanks in advance :) Have a nice day :)

Community
  • 1
  • 1
Stoimen
  • 649
  • 2
  • 8
  • 20

3 Answers3

3

You're looking to do a "deep copy." See Jon Skeet's answer here.

Community
  • 1
  • 1
NickAldwin
  • 11,584
  • 12
  • 52
  • 67
0

You'll have to implement a MyClass.Clone() function which creates copies of your instance. Then iterate thru all items in your source collection and add a clone to your target collection.

DanielB
  • 19,910
  • 2
  • 44
  • 50
-2

do not try to reinvent the wheel, use something already created. For such cases I use BLTookit, here http://bltoolkit.net/Doc.ObjectToObject.ashx or this AutoMapper here http://automapper.codeplex.com/.

Eugen
  • 2,934
  • 2
  • 26
  • 47
  • 2
    Rather than just posting links, you should explain how they help answer the question. – Gabe May 03 '11 at 16:38