Friday, May 12, 2023

Copy constructor in C#

 What is copy constructor in C#?


In C#, a copy constructor is a constructor method that creates a new object by copying the values of another object of the same type. The copy constructor is used to create a new instance of an object that has the same data as an existing object.


The copy constructor takes an object of the same type as a parameter, and it initializes the new object's data members with the same values as the existing object's data members.


Here's an example of a copy constructor:



class clsPerson

{

    public string Name { get; set; }

    public int Age { get; set; }


    public clsPerson()

    {

        // Default constructor

    }


    public clsPerson(Person other)

    {

        // Copy constructor

        Name = other.Name;

        Age = other.Age;

    }

}

```


In this example, the "clsPerson" class has a copy constructor that takes an object of the same type as a parameter. The constructor initializes the new object's "Name" and "Age" properties with the same values as the corresponding properties of the object passed in as a parameter.


You can create a new instance of the "clsPerson" class using the copy constructor as follows:



ClsPerson p1 = new clsPerson();

p1.Name = "Dheeraj Kumar";

p1.Age = 25;


ClsPerson p2 = new clsPerson(p1); // Create a copy of p1


In this example, the "p2" object is created using the copy constructor of the "clsPerson" class, which takes "p1" as a parameter. The "Name" and "Age" properties of "p2" are initialized with the same values as the corresponding properties of "p1".


Copy constructors are useful when you want to create a new object that is a copy of an existing object. They provide a way to create a new object with the same data as an existing object, without having to manually copy each data member or property.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...