Friday, August 10, 2007

Copy Constructor

COPY CONSTRUCTOR
• Copy Constructor is a Constructor that takes an instance of the class as its parameter and sets the data members to match the value of that instance
• C# does not provide a copy constructor

class Person
{
private string name;
private int age;

// Copy constructor.
public Person(Person previousPerson)
{
name = previousPerson.name;
age = 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, using Copy Constructor
Person person2 = new Person(person1);
System.Console.WriteLine(person2.Details);
}
}

No comments: