This can be used to clone an object. We can create our own interface IProtoType<T>
and specify a method of DeepCopy
which will remove the ambiguity we got from trying ICloneable but its would still mean traversing the object tree manually 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 implement IPrototype
- the nice thing now with IPrototype
is the API would return the given type so no casting is needed.
1 | public interface IPrototype<T> |
The implementation would be
1 | public class Person : IPrototype<Person> |
Example usage:
1 | var carl = new Person("Carl", new Address("Sale Street", 66)); |
Output would be:
1 | FirstName: Carl, Address: StreetName: Sale Street, HouseNumber: 66 |
References
- [PrototypePattern/ICloneableDemo.cs](https://github.com/carlpaton/Boilerplate/blob/master/.Net Core Console Application/PatternsAndPrinciples/PrototypePattern/ICloneableDemo.cs)
- https://docs.microsoft.com/en-us/dotnet/api/system.string
- https://docs.microsoft.com/en-us/dotnet/api/system.icloneable
- https://docs.microsoft.com/en-us/dotnet/api/system.icloneable.clone