Share via


How to: Write a Copy Constructor (C# Programming Guide)

Unlike some languages, 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.

Example

In this example, the Personclass contains a constructor that takes as its argument another object of type Person. The contents of the fields in this object are then assigned to the fields in the new object. An alternative copy constructor sends the name and age fields of the object to be copied to the instance constructor of the class.

class Person
{
    private string name;
    private int age;

    // Copy constructor. 
    public Person(Person previousPerson)
    {
        name = previousPerson.name;
        age = previousPerson.age;
    }

    //// Alternate copy contructor calls the instance constructor. 
    //public Person(Person previousPerson) 
    //    : this(previousPerson.name, previousPerson.age) 
    //{ 
    //} 

    // Instance constructor. 
    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    // Get accessor. 
    public string Details
    {
        get
        {
            return name + " is " + age.ToString();
        }
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a new person object.
        Person person1 = new Person("George", 40);

        // Create another new object, copying person1.
        Person person2 = new Person(person1);
        Console.WriteLine(person2.Details);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: George is 40

See Also

Concepts

C# Programming Guide

Reference

Classes and Structs (C# Programming Guide)

Constructors (C# Programming Guide)

Destructors (C# Programming Guide)

ICloneable