Copy Constructors

This can be used to clone an object however this is a C++ term, this allows you to specify an object to create the data from, it would not be very idiomatic for a C# developer so I don’t feel its the best approach for me as a .Net Developer.

Would require each custom type to have a copy constructor to allow traversing of the tree so the copy is done recursively. If you want to clone rather look at the suggestions under the creational Prototype Pattern.

Example

Example classes Person and Address which have copy constructors:

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
44
45
public class Person
{
public string FirstName;
public Address Address;

public Person(Person other)
{
FirstName = other.FirstName;
Address = new Address(other.Address);
}

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

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

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

public Address(Address other)
{
StreetName = other.StreetName;
HouseNumber = other.HouseNumber;
}

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

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

This will work as strings are immutable.

1
2
3
4
5
6
7
8
9
10
var carl = new Person("Carl", new Address("Sale Street", 66));
var john = new Person(carl)
{
FirstName = "John",
};
john.Address.HouseNumber = 123;
john.Address.StreetName = "Foo Street";

Console.WriteLine(carl);
Console.WriteLine(john);

Output would be:

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

References