camilo93.cc
camilo93.cc

Reputation: 147

How can I create a copy of an object using its constructor in c#?

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

Answers (3)

Hiran
Hiran

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

camelCase
camelCase

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

jProg2015
jProg2015

Reputation: 1128

ActionXML is reference type, you will also need to create a copy of ActionXML.

Here is a link to a web page explaining reference types vs value types.

Upvotes: 7

Related Questions