ICloneable

Creates a new object that is a copy of the current instance.

Caveat

Inheriting from and implementing this interface will provide a Clone method however the return type is object so would need to cast the result. This is not really ideal and could confuse the consumer. If you want to clone rather look at the suggestions under the creational Prototype Pattern.

Example

Example classes Person and Address which implement ICloneable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Person : ICloneable
{
public string FirstName;
public Address Address;

public Person(string firstName, Address address)
{
FirstName = firstName;
Address = address;
}

public object Clone()
{
return new Person(FirstName, (Address)Address.Clone());
}

public override string ToString()
{
return $"{nameof(FirstName)}: {FirstName}, {nameof(Address)}: {Address}";
}
}

public class Address : ICloneable
{
public string StreetName;
public int HouseNumber;

public Address(string streetName, int houseNumber)
{
StreetName = streetName;
HouseNumber = houseNumber;
}

public object Clone()
{
return new Address(StreetName, HouseNumber);
}

public override string ToString()
{
return $"{nameof(StreetName)}: {StreetName}, {nameof(HouseNumber)}: {HouseNumber}";
}
}

This will work as strings are immutable.

A string is a sequential collection of characters that is used to represent text. A String object is a sequential collection of System.Char objects that represent a string; a System.Char object corresponds to a UTF-16 code unit. The value of the String object is the content of the sequential collection of System.Char objects, and that value is immutable (that is, it is read-only). For more information about the immutability of strings, see the Immutability and the StringBuilder class section later in this topic. The maximum size of a String object in memory is 2GB, or about 1 billion characters. - microsoft.com

1
2
3
4
5
6
7
8
9
10
// Although this will work its a shallow copy
var carl2 = new Person("Carl", new Address("Sale Street", 66));
var john2 = (Person)carl2.Clone();

john2.FirstName = "John Two";
john2.Address.HouseNumber = 111;
john2.Address.StreetName = "Foo Street";

Console.WriteLine(carl2);
Console.WriteLine(john2);

Output would be:

1
2
FirstName: Carl, Address: StreetName: Sale Street, HouseNumber: 66
FirstName: John Two, Address: StreetName: Foo Street, HouseNumber: 111

References