2

Referring to a Stack overflow discussion related to creating the deep copy methods for a class using extension methods, which doesn't needs [Serializable] attribute:

How do you do a deep copy of an object in .NET (C# specifically)?

Class that I have is a singleton class, and it is an old implementation:

  • Can I create a deep copy of the same, I understand by definition it is not possible, but trying to understand, if there's a workaround that is possible in such a typical scenario. I understand that other option for me would be to change the class to non singleton, but in our current design and usage that would be lots of work and may lead to number of issues.

  • Also the current class has multiple other custom classes being referred, so when I am going for a deep copy, especially the way it is in the following code by Alex Burtsev:

https://raw.github.com/Burtsev-Alexey/net-object-deep-copy/master/ObjectExtensions.cs

Do I need to have the extension method for all the classes being referred, I am assuming that would be the case.

Community
  • 1
  • 1
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74

1 Answers1

5

A singleton class cannot have multiple instances by definition, as you mention. However there is no C# construct for a singleton class, so the implementation of a singleton class is already a workaround.

Even if your class only has a private constructor, you can use the BinaryFormatter (thanks Gusdor) or use reflection to create a deep copy]1.

In my opinion, a class is only a singleton class because you follow its behavior, so when you copy it, it is no longer a singleton class.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • I couldn't agree less. When you know it's your singleton, you won't try to deep copy it. When you know it's someone else's... Well, sometime the temptation is great. I don't know if this is the case that is referred to in the question, but it is the scenario I can think of for trying such a thing. – Andrei V Nov 21 '13 at 08:07
  • 1
    Why would you use reflection to deep copy when the `BinaryFormatter` is perfectly good? – Gusdor Nov 21 '13 at 08:14
  • @Gusdor You're right, my answer implied otherwise. The only difference is that `BinaryFormatter` skips the constructor, which probably is a good thing in this scenario. – C.Evenhuis Nov 21 '13 at 09:35