What is a copy constructor in C#?


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.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements