![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements