Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
NitinRank #140 · 16.1K reputationPosted Nov 22, 2022, 4:16 AM EST
A constructor that creates an object by copying variables from another object or that copies the data of one object into another object is termed as the Copy Constructor. It is a parameterized constructor that contains a parameter of the same class type.
C# Copy Constructor Syntax
class User
{
// Parameterized Constructor
public User(string a, string b)
{
// your code
}
// Copy Constructor
public User(User user) {
// your code
}
}
C# Copy Constructor Example
using System;
namespace Tutlane
{
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
// Copy Constructor
public User(User user)
{
name = user.name;
location = user.location;
}
}
class Program
{
static void Main(string[] args)
{
// User object with Parameterized constructor
User user = new User("Raj Kumar", "Hyderabad");
// Another User object (user1) by copying user details
User user1 = new User(user);
user1.name = "Goa Alavala";
user1.location = "Delhi";
Console.WriteLine(user.name + ", " + user.location);
Console.WriteLine(user1.name + ", " + user1.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
OutPut:
Raj Kumar, Hyderabad
Goa Alavala, Delhi
Press Any key to Exit
Vishal YelveRank #178 · 13.6K reputationPosted Nov 22, 2022, 4:35 AM EST
Copy Constructor creates an object by copying variables from another object.
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.
Onkar SharmaRank #104 · 20.6K reputationPosted Dec 25, 2022, 2:20 PM EST
Hi Naresh,
To know more about Copy Constructor in C#, visit:
Thanks!