#824 – A Copy Constructor Makes a Copy of an Existing Object
April 17, 2013 4 Comments
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);
I think in this case more correct to use interface ICloneable
@Skaarj – I won’t say “more correct”, although I’d suggest that if you were to write a copy constructor, you might as well throw in a ICloneable interface as well (since it’ll be a simple one-liner: public Object Clone() { return new Dog(this);} )
Actually, Microsoft has been advising against using ICloneable for 10 years: http://blogs.msdn.com/b/brada/archive/2003/04/09/49935.aspx
Pingback: #828 – Implementing Both a Copy Constructor and ICloneable | 2,000 Things You Should Know About C#
Pingback: #829 – Add Comments to Indicate Shallow vs. Deep Copying | 2,000 Things You Should Know About C#