October 7, 2008

[.NET] - Copy Constructors

We know that the manufacturer is a method that has the same name as the class and returns no value. 
It is used to initialize the data subject, we're creating.

There is another type of copy-builder the manufacturer. 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;
}

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.

No comments: