class Person{ private string name; private int age;
// Copy constructor. public Person(Person previousPerson) { name = previousPerson.name; age = previousPerson.age; }
// Instance constructor. public Person(string name, int age) { this.name = name; this.age = age; }
// Get accessor. public string Details { get { return name + " is " + age.ToString(); } }}
class TestPerson{ static void Main() { // Create a new person object. Person person1 = new Person("George", 40);
// Create another new object, copying person1. Person person2 = new Person(person1); System.Console.WriteLine(person2.Details); }}
[ComVisibleAttribute(true)] public interface ICloneable
Account clonedAccount = new Account(currentAccount); // Deep or shallow?
Account clonedAccount = currentAccount.DeepClone(); // instance method orAccount clonedAccount = Account.DeepClone(currentAccount); // static method
class CheckingAccount : Account { CheckAuthorizationScheme checkAuthorizationScheme; public override Account DeepClone() { CheckingAccount clone = new CheckingAccount(); DeepCloneFields(clone); return clone; } protected override void DeepCloneFields(Account clone) { base.DeepCloneFields(clone); ((CheckingAccount)clone).checkAuthorizationScheme = this.checkAuthorizationScheme.DeepClone(); } }
-------------------------------------------------------------------------------
public class Employee:ICloneable { /// <summary> /// Gets or Sets the Employee ID /// </summary> public int EmployeeId { get; set; } /// <summary> /// Gets or Sets Employee Name /// </summary> public string EmployeeName { get; set; } /// <summary> /// Gets or Sets the Joining Date /// </summary> public DateTime JoiningDate { get; set; } /// <summary> /// Gets or Sets the DepartmentDetail object /// </summary> public DepartmentDetail Department { get; set; } ///
/// Returns the Deep Copied object /// </summary> /// <returns></returns> public object Clone() { Employee employee = (Employee)this.MemberwiseClone(); employee.Department = new DepartmentDetail(); return employee; } }
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.