0

I have an object with lists inside. I need to copy that object value without copying its reference. To explain further, I can edit the original object but the duplicate object should not be altered.

How can i solve this?

jps
  • 15,760
  • 14
  • 59
  • 71
  • Does this answer your question? [Deep cloning objects](https://stackoverflow.com/questions/78536/deep-cloning-objects) – shingo May 24 '22 at 11:13
  • The most elegant way in my opinion is to implement ICloneable interface in your class and use copy constructor to make a deep copy in Clone() method as suggested by my predecessor's. We don't know how the class looks like so we can't provide specific implementation. – Artur May 24 '22 at 11:43
  • So you want deep clone with copy on the write? – Aluan Haddad May 24 '22 at 11:51
  • McNets Why do u want to write so much of code for small task. the links u shared may be are getting the work done but i am finding the simplest way of doing. Thanks for your inputs and time. – Siva Sagar Jagga May 25 '22 at 08:09
  • BTW thanks everyone for your inputs, got it worked. – Siva Sagar Jagga May 25 '22 at 08:11

1 Answers1

0

This is so simple, No need of using some cloning method and inheriting iclonable and all.

I am using .NET 6.0.

var duplicateObject = new List<ClassName>(OldObject);

This will automatically create a new duplicateObject by deep coping OldObject. By editing the OldObject it doesnot affect the duplicateObject and can be used as backup object or adding some of the removed items back to the OldObject when it is functionally needed.