Copy constructor and IClonable

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);
}
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.