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. The main use of copy constructor is to initialize a new instance to the values of an existing instance. Normally, C# does not provide a copy constructor for objects, but if you want to create a copy constructor in your program you can create according to your requirement.
Syntax:
class Class_Name {
// Parameterized Constructor
public Class_Name(parameter_list)
{
// code
}
// Copy Constructor
public Class_Name(Class_Name instance_of_class)
{
// code
}
}
Example 1:
CSharp
using System;
namespace simplecopyconstructor {
class technicalscripter {
private string topic_name;
private int article_no;
public technicalscripter( string topic_name, int article_no)
{
this .topic_name = topic_name;
this .article_no = article_no;
}
public technicalscripter(technicalscripter tech)
{
topic_name = tech.topic_name;
article_no = tech.article_no;
}
public string Data
{
get
{
return "The name of topic is: " + topic_name +
" and number of published article is: " +
article_no.ToString();
}
}
}
public class GFG {
static public void Main()
{
technicalscripter t1 = new technicalscripter( " C# | Copy Constructor" , 38);
technicalscripter t2 = new technicalscripter(t1);
Console.WriteLine(t2.Data);
Console.ReadLine();
}
}
}
|
Output:
The name of topic is: C# | Copy Constructor and number of published article is: 38
Example 2:
CSharp
using System;
namespace copyConstructorExample {
class Vehicle {
private string name;
private string color;
private int quantity;
public Vehicle(Vehicle a)
{
name = a.name;
color = a.color;
quantity = a.quantity;
}
public Vehicle( string name, string color, int quantity)
{
this .name = name;
this .color = color;
this .quantity = quantity;
}
public string DetailsofVehicle
{
get
{
return "Type: " + name.ToString() +
"\nColor: " + color.ToString() +
"\nQuantity: " + quantity.ToString();
}
}
public static void Main()
{
Vehicle v1 = new Vehicle( "Bike" , "Black" , 40);
Vehicle v2 = new Vehicle(v1);
Console.WriteLine(v2.DetailsofVehicle);
}
}
}
|
Output:
Type: Bike
Color: Black
Quantity: 40