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:


ICloneable:
* Implementing ICloneable in a class

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
123 ICloneable
127 Caching
135 Pointers
147 C# Script