1

As stated on the Microsoft's site, ICloneable interface can either deep or shallow copy:

An implementation of Clone can perform either a deep copy or a shallow copy. In a deep copy, all objects are duplicated; in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.

To be honest, since there is not additional explanation on the topic, I don't understand how am I going to know when will shallow or deep copying occur?

aca
  • 1,071
  • 5
  • 15
  • 5
    You don't, and that's a reason that interface is terrible. – Magnetron Feb 06 '23 at 14:40
  • 2
    The very next line from the section you quoted: "Because callers of Clone cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs." – Joe Sewell Feb 06 '23 at 14:41
  • 1
    @JoeSewell I'm not using APIs in the data that I need to deep copy. – aca Feb 06 '23 at 14:44
  • 1
    @Magnetron I've found an [article](https://learn.microsoft.com/en-us/archive/blogs/brada/should-we-obsolete-icloneable-the-slar-on-system-icloneable) (from the 2004. lol) about discussion regarding this interface, and I can't believe that there is basically no improvement since – aca Feb 06 '23 at 14:46
  • 3
    The point is - if you are both the *implementer* and the *caller* of the interface in some non-public types, you can implement this interface and you'll know the answer. As soon as that's not true, it fails to be useful. That's what the warning against public APIs is, I believe, trying to say. – Damien_The_Unbeliever Feb 06 '23 at 14:58
  • 1
    The reason there's been no improvement since 2004 is because it was a bad idea from the start, and it can't be fixed. – Matthew Watson Feb 06 '23 at 15:38

1 Answers1

2

You can't - one of several reasons why this API is basically unusable except perhaps in your own models when you know and control everything, and in those scenarios: you can use your own clone API (perhaps even strongly typed!).

The framework does not provide any API for this scenario; you might be able to use a serializer library as a deep-clone equivalent, although that might be less efficient than you'd like.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    @aca I have implemented this interface, a long time ago, before .Net 2.0. I now mentally file it next to `ArrayList`. – Jodrell Feb 06 '23 at 16:19
  • Yeah, serializer won't work. I mean, I have a really huge and complex model that should be cloned, and TBH, after 3 weeks of researching and trying, I feel like I am going to give up. – aca Feb 07 '23 at 08:25