Copy Constructors
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Contents |
[edit]
Copying a class
C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself. For example:
class Car { private string plate; private int mileage; // Copy constructor. public Car(Car previousCar) { plate = previousCar.plate; mileage = previousCar.mileage; } // Instance constructor. public Car(string plate, int mileage) { this.plate = plate; this.mileage = mileage; } // Get accessor. public string Details { get { return "The car : " + plate + " has done " + mileage.ToString() + " miles"; } } } class TestCar { static void Main() { // Create a new car object. Car car1 = new Car("BB06 YUK", 40000); // Create another new object, copying car1. Car car2 = new Car(car1); System.Console.WriteLine(car2.Details); } }
[edit]
An alternative
This is a simple way to copy an object; however, an alternative method is to implement the ICloneable interface.
[edit]
MSDN references
|

