#828 – Implementing Both a Copy Constructor and ICloneable

A copy constructor is a constructor that creates a new object by making a copy of an existing object.  ICloneable is a standard interface that you can implement, whereby you’ll add a Clone method to your class.  The purpose of the Clone method is to make a copy of the existing object.

Neither a copy constructor nor the ICloneable interface dictates whether you make a shallow or a deep copy of an object.

Your class can implement both methods for making a copy of an object.

    public class Dog : ICloneable
        public string Name { get; set; }
        public int Age { get; set; }

        // Standard constructor
        public Dog(string name, int age)
            Name = name;
            Age = age;

        // Copy constructor (shallow copy)
        public Dog(Dog otherDog)
            Name = otherDog.Name;
            Age = otherDog.Age;

        // ICloneable
        public object Clone()
            return new Dog(this);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: