Unlike some languages, C# does not provide a copy constructor.
If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.
Copy constructor implementation support ‘Deep Copy’. i.e Change in one does not affect the other.
class Employee { public int age; public string city; // Instance constructor public Employee(int age, string city) { this.age = age; this.city = city; } // Copy constructor public Employee(Employee obj) { age = obj.age; city = obj.city; } public string Details { get { return " Age is: " + age.ToString() + " City is: " + city; } } } | void main() { Employee emp1 = new Employee(55," Employee emp2 = new Employee(emp1); // Explicit call to Copy Constructor MessageBox.Show(emp1.Details); // 55 & emp2.age = 66; MessageBox.Show(emp1.Details); // 55 & // Here No Change as its a Deep copy } Note – The C++ approach below. Employee emp2; emp2 = emp1; In C++, this assignment statement automatically makes call to Copy Constructor and will provide a Shallow copy. But in C# this approach will not call the defined Copy Constructor. Reason - C# does not provide a copy constructor. Hence this will result in Shallow Copy. |
Regards,
Arun Manglick
No comments:
Post a Comment