Why use clone ()?

What is the main purpose of using Clone () in C #?

What is the advantage of using it?

+4
source share
3 answers

The idea is that with Clone you can create a new object of the same type as the one you are calling it with, without knowing the exact type of object you are calling it to.

For instance:

 void Test(ICloneable original) { var cloned = original.Clone(); } 

Here, cloned has the same runtime type as original , and you did not need to know that this type should perform cloning.

However, the usefulness of ICloneable almost does not exist, since it does not determine the semantics of the clone operation: is it a shallow copy or a deep copy ? Since the interface does not respond to one or the other, you cannot really know what you are getting. And since knowing that this is important because you need to handle the clone accordingly, ICloneable itself is a very burnt card.

Defining your own interface using the Clone method (with well-defined semantics) makes sense.

Update: See also: Why should I implement ICloneable in C #?

+14
source

Clone() usually provides a shallow copy of an object (i.e. see Array.Clone () ), it copies links, but not referencing objects.

This is convenient if you understand its limitations, mainly that the semantics of what is actually copied to the new object are mainly provided to the developer of the Clone() method, because the ICloneable interface that defines the Clone() method is underdetermined (so it may be a shallow copy or a deep copy, but you cannot rely on them).

+3
source

When we copy the contents of an object to another (SomeClass obj2 = obj1), obj2, also belonging to the same class, changing the contents of obj2 also changes the contents of obj1. This is because they are reference types. Using Clone () (appropriately) can avoid this. If you modify the cloned object, the original will not be changed.

0
source

Source: https://habr.com/ru/post/1345345/


All Articles