Thursday, January 5, 2012

What is Copy Constructors?

Copy Constructor

Constructor - A method that has the same name as the class and returns no value. It is used to initialize the data in the object we're creating Copy Constructor - When we copy one objectto another, C# will copy the reference to the first object to the new object, its mean that now we have two references to the same object. To make an actual copy, we can use a copy constructor, which is just a standard constructor that takes an object of the current class as its single parameter.

For Eg-
public ClassA(ClassA objClass)
{
this.student = objClass.student;
}



 Now we can use this constructor to create copies. The copy will be a separate object, not just a reference to the original object.


class ClassA
{
private string student;
public ClassA(string student)
{
this.student = student;
}
public ClassA(ClassA objClass)
{
this.student = objClass.student;
}
public string Student
{
get{ return student; }
set { student = value; }
}
}

Now
class Result
{
static void Main()
{
ClassA objClass = new ClassA("ABC");
ClassA newObjClass = new ClassA(objClass);
objClass.Student = "MNO";
Console.WriteLine("The New Class name is {0}", newObjClass.Student);
}
}




Here Output : -

The New Class name is ABC.