11

Possible Duplicate:
Cloning objects in C#

I have a class with properties and some of them are reference types (instances of other classes) themselves (CookieContainer).

I want to have a exact copy of this class so any change to previous version would not affect this new instance.

Is there a general solution for this kind of problems or I should do it manually ?

Community
  • 1
  • 1
Xaqron
  • 29,931
  • 42
  • 140
  • 205

2 Answers2

10

You need to deep copy the object to another object. There are many approaches to this but serializing one object and deserializing that data into another object is a very quick trick to achieve this. See it here: How do you do a deep copy of an object in .NET (C# specifically)?

Community
  • 1
  • 1
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
-2

Decide how deep you want your copy and implement the ICloneable interface and Clone method: https://learn.microsoft.com/en-us/dotnet/api/system.icloneable

rtalbot
  • 1,615
  • 10
  • 13