What is a copy constructor in C#?

CsharpProgrammingServer Side Programming

Copy Constructor creates an object by copying variables from another object.

Let us see an example −

Example

using System;
namespace Demo {
   class Student {
      private string name;
      private int rank;

      public Student(Student s) {
         name = s.name;
         rank = s.rank;
      }

      public Student(string name, int rank) {
         this.name = name;
         this.rank = rank;
      }

      public string Display {
         get {
            return " Student " + name +" got Rank "+ rank.ToString();
         }
      }
   }

   class StudentInfo {
      static void Main() {
         Student s1 = new Student("Jack", 2);

         // copy constructor
         Student s2 = new Student(s1);

         // display
         Console.WriteLine(s2.Display);
         Console.ReadLine();
      }
   }
}

Above we saw, firstly we declared a copy constructor −

public Student(Student s)

Then a new object is created for the Student class −

Student s1 = new Student("Jack", 2);

Now, the s1 object is copied to a new object s2 −

Student s2 = new Student(s1);

This is what we call copy constructor.

raja
Published on 13-Aug-2018 11:52:29
Advertisements