Implementing ICloneable in a struct
suggest changeThe 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 also need copying. [ImmutableObject(true)] is only a designer hint. It does not make the struct immutable.
// Structs are recommended to be immutable objects
[ImmutableObject(true)]
public struct Person : ICloneable
{
// Contents of the struct
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);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents