Abdullah
Abdullah

Reputation: 637

Create copy of object (on inheritance)

I have a method for creating copy of object

protected Node CreateCopy()
{
    return new Node(InputCount, OutpuCount, Name);;
}

And some child class like this:

public class SuperNode: Node { ... }

public class CoolNode: Node { ... }

Is there a way to automatically create copies of them?

(need type of child class not base)

Upvotes: 0

Views: 119

Answers (2)

shay__
shay__

Reputation: 3990

Thomas Levesque's answer is great if you need a copy of the base class. But since you asked for the child type, I'll just add this classic OOP suggestion:

class Node 
{
    protected int _num;
    protected string _text;

    public Node(int num, string text)
    {
        _num = num;
        _text = text;
    }

    public virtual Node Clone()
    {
        return new Node(_num, _text);
    }
}

class SuperNode : Node
{
    DateTime _superTime;

    public SuperNode(int num, string text, DateTime time)  :base(num, text)
    {
        _superTime = time;
    }

    public override Node Clone()
    {
        return new SuperNode(_num, _text, _superTime);
    }
} 

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292405

Is there a way to automatically create copies of them ?

You can use the MemberwiseClone method inherited from Object:

protected Node CreateCopy()
{
    return (Node)MemberwiseClone();
}

Note that it will be a shallow copy, i.e. reference type members will be copied by reference, not cloned.

If you need a deep copy, you can serialize and deserialize the object (not very efficient very inefficient, and only works for serializable types), or use a tool like AutoMapper.

Upvotes: 4

Related Questions