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 | public class Person : ICloneable |
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 | // Although this will work its a shallow copy |
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