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

c#

Solution

In general you should avoid putting mutable reference types like Array into structs. See this question and answer.

So make your class a reference type and give it a DeepCopy method. Or even better - make your type immutable so that you don't need to make a copy.

Problem

If have a ``` struct A { public double[] Data; public int X; } ``` How can I force a deep copy when using `operator=` or adding instances of `A` to a 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 have to implement my own `DeepClone` method and call it every time? This would be extremly error-prone ...

Original source

Related problems