Reputation: 147
I'm trying to create a copy of an object using its constructor but when I modify something of the copy, the original object is modified too. I'll be grateful if you can help me, this is my code:
public class XMLStructure
{
public XMLStructure(XMLStructure xmlCopy )
{
this.Action = xmlCopy.Action;
this.Name = xmlCopy.Name;
}
public String Name { get; set; }
public ActionXML Action { get; set; }
}
Upvotes: 0
Views: 216
Reputation: 1180
you need to do same (add constructor, that allows to copy) for ActionXML and any other reference type variable in that class.
Upvotes: 1
Reputation: 1780
You need to "deep clone" the object to avoid the problem you have observed. The accepted method for doing this in .Net has evolved over the years. Today the simplest option is to serialise an object out to a JSON string and then hydrate a new object from that JSON string.
var json = JsonConvert.SerializeObject(xmlSourceObject );
var clonedXmlObject = JsonConvert.DeserializeObject<XMLStructure>(json);
The more traditional .Net solution is to implement the ICloneable interface.
Upvotes: 1