C# | Copiar constructor – Part 1

Un constructor que crea un objeto copiando variables de otro objeto o que copia los datos de un objeto en otro objeto se denomina Copy Constructor . Es un constructor parametrizado que contiene un parámetro del mismo tipo de clase. El uso principal del constructor de copias es inicializar una nueva instancia con los valores de una instancia existente. Normalmente, C# no proporciona un constructor de copia para objetos, pero si desea crear un constructor de copia en su programa, puede crearlo de acuerdo con sus requisitos.
Sintaxis: 
 

class Class_Name {

        // Parameterized Constructor
        public Class_Name(parameter_list)
        {

            // code

        }

        // Copy Constructor
        public Class_Name(Class_Name instance_of_class)
        {

            // code

        }

    }

Ejemplo 1:

CSharp

// C# program to illustrate the use
// of copy constructor
using System;
 
namespace simplecopyconstructor {
 
class technicalscripter {
 
    // variables
    private string topic_name;
    private int article_no;
 
    // parameterized constructor
    public technicalscripter(string topic_name, int article_no)
    {
        this.topic_name = topic_name;
        this.article_no = article_no;
    }
 
    // copy constructor
    public technicalscripter(technicalscripter tech)
    {
        topic_name = tech.topic_name;
        article_no = tech.article_no;
    }
 
    // getting the topic name and
    // number of articles published
    public string Data
    {
 
        get
        {
            return "The name of topic is: " + topic_name +
                   " and number of published article is: " +
                                    article_no.ToString();
        }
    }
}
 
// Driver Class
public class GFG {
 
// Main Method
static public void Main()
{
 
    // creating object t1
    // and provide value to the object
    technicalscripter t1 = new technicalscripter(" C# | Copy Constructor", 38);
 
    // Creating object t2 and
    // copy the data of t1 object
    // into t2 object
    technicalscripter t2 = new technicalscripter(t1);
 
    Console.WriteLine(t2.Data);
    Console.ReadLine();
}
}
}

Producción:

The name of topic is:  C# | Copy Constructor and number of published article is: 38

Ejemplo 2:

CSharp

// C# Program to illustrate the use
// of Copy constructor
using System;
 
namespace copyConstructorExample {
 
class Vehicle {
 
    // variables
    private string name;
    private string color;
    private int quantity;
 
    //  Copy constructor
    public Vehicle(Vehicle a)
    {
        name = a.name;
        color = a.color;
        quantity = a.quantity;
    }
 
    // Parameterized constructor
    public Vehicle(string name, string color, int quantity)
    {
        this.name = name;
        this.color = color;
        this.quantity = quantity;
    }
 
    // Get details of Vehicles
    public string DetailsofVehicle
    {
        get
        {
            return "Type: " + name.ToString() +
                   "\nColor: " + color.ToString() +
                   "\nQuantity: " + quantity.ToString();
        }
    }
 
    // Main Method
    public static void Main()
    {
 
        // Create a new object.
        Vehicle v1 = new Vehicle("Bike", "Black", 40);
 
        // here is v1 details are copied to v2.
        Vehicle v2 = new Vehicle(v1);
 
        Console.WriteLine(v2.DetailsofVehicle);
    }
}
}

Producción: 

Type: Bike
Color: Black
Quantity: 40

Publicación traducida automáticamente

Artículo escrito por ankita_saini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *