Home > Software design >  Deep copy a node in C#
Deep copy a node in C#

Time:12-16

So long story short I have a tree with Nodes. I have to copy the information of one Node to another, but when I change the second Node, the fisrt changes too. I have made this method in the Node class :

public Node DeepCopyNode(Node node)
{
    Node newNode = new Node(node.Name, node.NodeТype, node.ParentExist, node.TagArguments, node.Parent, node.Children, node.NumberInCount);

    for (int i = 0; i < node.Children.Count; i  )
    {
        if (node.Children[i] != null)
        {
            DeepCopyNode(node.Children[i]);
        }
    }
    return newNode;
}

I tried to make Deep copy of the Node, but unfortunately didn't work. If somebody have any suggestions what to do, please write it down :)

CodePudding user response:

The simplest way to make a deep copy of an object is to deserialize it's serialized version:

var newNode = JsonConvert.DeserializeObject<Node>(JsonConvert.SerializeObject(node));

CodePudding user response:

Node newNode = new Node(... node.Parent, node.Children ...);

This is wrong. You cannot use the parent or children of the node you are copying if you want a deep copy. It should look something like

public Node DeepCopyNode(Node node, Node parent)
{
    Node newNode = new Node(..., parent, new List<Node>(), ...);
    var children = node.Children.Select(c => DeepCopyNode(c, newNode )).ToList();
    newNode.Children.AddRange(children); 
    return newNode;          
}

All this assumes only the tree needs deep copying, not any other values stored in the tree.

  • Related