4

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 ...

Danvil
  • 22,240
  • 19
  • 65
  • 88

3 Answers3

3

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.

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • +1: It's good to keep simple classes immutable, if you can, as it reduces the possibility for error when using them. For instance, even if you implement a Deep Copy, there is no guarantee that the consumer of your code will actually use it. With structs, in particular, mutability is quite unexpected. – Dan Bryant Apr 24 '10 at 21:57
1

You need to implement the deep copy method yourself.

Quite often API designers design a Clone(), Clone(bool deep), or Copy() method to do this.

ICloneable is used sometimes to mark class is cloneable, but it can be confusing since it doesn't specify if the Clone() method is deep or shallow. Why should I implement ICloneable in c#?.

Community
  • 1
  • 1
kervin
  • 11,672
  • 5
  • 42
  • 59
0

No way to do that. You need to implement your own deep copy mechanism.

zumalifeguard
  • 8,648
  • 5
  • 43
  • 56