Implementing ICloneable in a struct

suggest change

The implementation of ICloneable for a struct is not generally needed because structs do a memberwise copy with the assignment operator =. But the design might require the implementation of another interface that inherits from ICloneable.

Another reason would be if the struct contains a reference type (or an array) which would need copying also.

// Structs are recommended to be immutable objects
[ImmutableObject(true)]
public struct Person : ICloneable
{
    // Contents of class
    public string Name { get; private set; }
    public int Age { get; private set; }
    // Constructor
    public Person(string name, int age)
    {
        this.Name=name;
        this.Age=age;
    }
    // Copy Constructor
    public Person(Person other)
    {
        // The assignment operator copies all members
        this=other;
    }

    #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:

static void Main(string[] args)
{
    Person bob=new Person("Bob", 25);
    Person bob_clone=bob.Clone();
    Debug.Assert(bob_clone.Name==bob.Name);
}

Feedback about page:

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


ICloneable:
* Implementing ICloneable in a struct

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