What do you mean by copy constructor in C# ?
Loading
What do you mean by copy constructor in C# ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Onkar SharmaPosted Dec 25, 2022, 7:20 PM
Hi Naresh,
To know more about Copy Constructor in C#, visit:
Thanks!
Vishal YelvePosted Nov 22, 2022, 9:35 AM
Copy Constructor creates an object by copying variables from another object.
Above we saw, firstly we declared a copy constructor
Then a new object is created for the Student class
Now, the s1 object is copied to a new object s2
This is what we call copy constructor.
NitinPosted Nov 22, 2022, 9:16 AM
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