C# Language Implementing ICloneable in a struct


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
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)
    // Copy Constructor
    public Person(Person other)
        // The assignment operator copies all members

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

Later to be used as follows:

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