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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 = <span class="skimlinks-unlinked">otherDog.Name</span>; Age = <span class="skimlinks-unlinked">otherDog.Age</span>; }} |
Example of using the copy constructor:
1 2 3 4 5 | // Create a dogDog myDog = new Dog("Kirby", 15);// Create a copy of KirbyDog other = new Dog(myDog); |

