#824 – A Copy Constructor Makes a Copy of an Existing Object

A copy constructor is a constructor that you can define which initializes an instance of a class based on a different instance of the same class.

In the example below, we define a copy constructor for Dog.  The constructor creates a new instance of a Dog based on an existing instance.

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

        // Constructor that takes individual property values
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Copy constructor
        public Dog(Dog otherDog)
        {
            Name = otherDog.Name;
            Age = otherDog.Age;
        }
    }

Example of using the copy constructor:

            // Create a dog
            Dog myDog = new Dog("Kirby", 15);

            // Create a copy of Kirby
            Dog other = new Dog(myDog);

824-001

Advertisement

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

4 Responses to #824 – A Copy Constructor Makes a Copy of an Existing Object

  1. Skaarj says:

    I think in this case more correct to use interface ICloneable

  2. Pingback: #828 – Implementing Both a Copy Constructor and ICloneable | 2,000 Things You Should Know About C#

  3. Pingback: #829 – Add Comments to Indicate Shallow vs. Deep Copying | 2,000 Things You Should Know About C#

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: