How to force a deep copy when copying structures with arrays?

If there is

struct A { public double[] Data; public int X; } 

How can I force a deep copy when using operator= or add instances of A to the container?

The problem is, for example:

 A a = new A(); var list = new List<A>(); list.Add(a); // does not make a deep copy of Data A b = a; // does not make a deep copy of Data 

Do I really need to implement my own DeepClone method and call it every time? That would be extremely error prone ...

+4
source share
3 answers

In general, you should avoid placing link types in structured variables, such as Array. See this question and answer.

So make your class a reference type and give it a DeepCopy method. Or better yet, make your type immutable so you don't have to make a copy.

+3
source

You need to implement the deep copy method yourself.

Quite often, API designers develop a Clone (), Clone (bool deep), or Copy () method for this.

ICloneable is sometimes used to indicate that a class is cloned, but can be confusing because it does not indicate whether the Clone () method is deep or shallow. Why should I implement ICloneable in C #? .

+1
source

There is no way to do this. You need to implement your own deep copy engine.

0
source

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


All Articles