Saturday, April 21, 2012

Copy Constructors in C#


Copy Constructors
Copy constructor creates an object by copying variables from another object.
When you copy one object to another, C # allows you to copy the reference to the first objection to the new object, which means that we now have two references to the same object.

To make a real copy, we can use a copy constructor, which is just a standard constructor that takes an object of class as its only parameter. For example, that a copy constructor of the class of students might look. Note that we copy the domain name for the new object.

public Student(Student student)
{
   this.name = student.name;
}

Student objStudent2 = new Student(objStudent2);


Now we can use this constructor to create a copy. The copy is another object, not just a reference to the original object.

        class Student
        {

            private string name;

            public Student(string name)
            {

                this.name = name;

            }

            public Student(Student student)
            {

                this.name = student.name;

            }

            public string Name
            {

                get
                {

                    return name;

                }

                set
                {

                    name = value;

                }

            }

        }



        class Final
        {

            static void Main()
            {

                Student student = new Student("A");

                Student NewStudent = new Student(student);

                student.Name = "B";

                System.Console.WriteLine("The new student's name is {0}", NewStudent.Name);

            }

        }


The new student's name is A.

0 comments: