C# Clone a specialized TreeNode containing another Object of type Object

299 Views Asked by At

I have been searching for a simple solution for a cloning of an object containing other objects.

public class TPFTestCaseTreeNode: TreeNode, ICloneable
{
    public Object Obj;

    public TPFTestCaseTreeNode(string Title, Object O)
    {
        // Set attributes for the TreeNode
        Text = Title; // not sure which one we need
        Name = Title; // not sure which one we need

        // And additionally, remember the test case object
        Obj = O;
    }
} 

For Cloning, I am using :

foreach(TreeNode t in listAllTestCases)
{
    if(t.Name.Equals(testCaseIdDesc))
    {
        theNode = (TreeNode)((ICloneable)t).DeepClone();                     
    }
}

listAllTestCases contain all the tree nodes of type "TPFTestCaseTreeNode".

"t" in the loop, does contain valid value for "Obj" as per debugger mode

I have tried the normal Clone() and DeepClone() as well, none of them was able to clone the state of the Object "Obj". It always remains null in the cloned object treenode "theNode".

Can anyone provide a plausible explanation why the cloning of an object containing another object is failing here? Here are the two states Initial before cloning and after cloning. Initial State Cloned Object

Please note that I have even tried the binaryformatter(serialize/ deserialize mechanism) as well. But still, Object "Obj" is null.

1

There are 1 best solutions below

0
satyadev On

So Finally, I had to use the Treenode "Tag" property itself and assign my "Obj" to it. However here as well DeepClone() or Clone() did not clone this Tag Property value.

Basically I had to loop on each property of the actual object and build the cloned one.

Such a hassle for custom types of Treenode, but it is working fine now.

Thanks all for the valuable inputs.