Implementing ICloneable in a struct C# with Example



Implementing ICloneable in a struct C# with Example

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); 
} 
 

0 Comment's

Comment Form