Search code examples
c#derivedconstruct

C#: How to construct a derived class from an existing base class object?


Consider this, please:

class MyTreeNode: TreeNode{
   int x;
   public MyTreeNode(TreeNode tn)
   {
      x=1; 
      // Now what to do here with 'tn'???
   }

I know how to use x. But how should I use tn here to assign it to my MyTreeNode object?


Solution

  • Why do you want to assign the tn to your MyTreeNode? It allready inherits from it. If you´re planning to create a copy of tn but of type MyTreeNode you should create a copy-constructor:

    int x;
    public MyTreeNode(TreeNode tn)
    {
        // copy tn´s attributes first
        this.myProp = tn.myProp;
        // ... all the other properties from tn
    
        // now set the value for x
        this.x = 1; 
    }
    

    However if you also have private members on your base-class which have to be copied this is much more difficult, you´d have to use reflection in this case to have access to those private members (e.g. fields).