0

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; }
}
13
  • Well the string is indeed copied, but the ActionXML will still reference the original Commented Jul 21, 2017 at 14:58
  • 2
    That wasn't a duplicate Servy Commented Jul 21, 2017 at 15:03
  • 1
    Tempted to hammer as stackoverflow.com/questions/78536/deep-cloning-objects Commented Jul 21, 2017 at 15:05
  • 1
    @servy: the topic of this question is: why does this copy-constructor doesn't work as expected? Answer: Because it is half-finished. The question of the related question was: why is my original instance changed if i pass a copy to a method that changes it? Answer: because it is not a copy at all but the same reference. Commented Jul 21, 2017 at 15:15
  • 2
    There is much advice here on the need to clone the Action property but no one has suggested using String.Copy() for the name property to ensure the Name property of the new cloned object is a genuine independent copy of the string. I appreciate this is an edge case due to immutable .Net strings but feel a mention of String.Copy() adds to the discussion. Commented Jul 21, 2017 at 15:38

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

you need to do same (add constructor, that allows to copy) for ActionXML and any other reference type variable in that class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.