Copy Constructors

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents


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


An alternative

This is a simple way to copy an object; however, an alternative method is to implement the ICloneable interface.


MSDN references


Previous_Page_.gif Next_Page_.gif

Personal tools