Implementing ICloneable in a class

suggest change

Implement ICloneable in a class with a twist. Expose a public type safe Clone() and implement object Clone() privately.

public class Person : ICloneable
{
    // Contents of class
    public string Name { get; set; }
    public int Age { get; set; }
    // Constructor
    public Person(string name, int age)
    {
        this.Name=name;
        this.Age=age;
    }
    // Copy Constructor
    public Person(Person other)
    {
        this.Name=other.Name;
        this.Age=other.Age;
    }

    #region ICloneable Members
    // Type safe Clone
    public Person Clone() { return new Person(this); }
    // ICloneable implementation
    object ICloneable.Clone()
    {
        return Clone();
    }
    #endregion
}

Later to be used as follows:

{
    Person bob=new Person("Bob", 25);
    Person bob_clone=bob.Clone();
    Debug.Assert(bob_clone.Name==bob.Name);

    bob.Age=56;
    Debug.Assert(bob.Age!=bob.Age);
}

Notice that changing the age of bob does not change the age of bob_clone. This is because the design uses cloning instead of assigning of (reference) variables.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents