Why does ICloneable not guarantee the correct clone? — a better approach
In the following, we will discuss the problems with ICloneable and talk about a better alternative in C#.
ICloneable
built-in interface supports cloning, which creates a new instance of a class with the same value as an existing instance. The ICloneable
contains one method, the Clone()
, which is intended to provide cloning support.
What are the main problems with ICloneable?
1. Time-consuming to implement: if you have a deep hierarchy of objects, you will have to create a lot of interface implementation and deep copy logic for every member.
2. Ambiguous specification: the Clone()
method is not required to implement a deep copy strategy and therefore it is not clear if the clone is implemented as a deep- or as a shallow copy.
If you don’t know what is the difference between a deep copy and a shallow copy check my article about this topic here.
3. Unnecessary casting: the ICloneable
Clone()
method returns a weakly typed object which requires casting back into the original stronger type.
A simplified solution
One of the easiest way to create a full deep clone is to serialize an object and then deserialize it back into a new object. For this, you can use the built-in JSON serializer or the Microsoft.AspNetCore.Mvc.NewtonsoftJson
Nuget package like in the following example.
Using NewtonsoftJson with extension method:
Using in the same namesapce:
Conclusion
Serializing and deserializing the object is a great way to create a clone because it automatically makes a deep copy of the object. Also, it is flexible to implement. You can use a Binary, XML, or JSON Formatter, etc. Furthermore, it does not require any interface.
Of course, this approach is not perfect either. It can cause performance issues and runtime errors if the object cannot be easily serialized/deserialized.
Hi, guys, I’m Roland and I’m here to share with all of you my passion for development, computer engineering, project management, personal development, hobbies, and everything in between.
Feel free to contact me anytime — I would love to exchange new ideas and inspire each other!