7

I have a function that takes an object from a list as a parameter. I create a new instance of this object and make it equal to the object passed into the function. I change some of the properties of the new object, but these changes also get applied to the original object in the list. Example:

public void myFunction(Object original)
{
    var copyOfObject = original;

    copyOfObject.SomeProperty = 'a';
}

From reading, I guess I am creating a shallow copy of my original object, so when I update the properties on my new object this causes the properties on the original to change to? I've seen some examples of copying the entire list of objects to create a deep copy, but I only want to create a deep copy of this single object and not the entire list. Can I do this without having to do:

  copyOfObject = new Object();
  copyOfObject.someProperty = original.someProperty;

before making my changes?

Meridian
  • 111
  • 1
  • 1
  • 4
  • https://stackoverflow.com/questions/78536/deep-cloning-objects?rq=1 – Sebastian Hofmann Mar 14 '18 at 11:20
  • better you use copy constructor, that would be much in your control. – Amit Mar 14 '18 at 11:21
  • Indeed, smells like closing – TheGeneral Mar 14 '18 at 11:22
  • You can serialize and deserialize your object. You will get another object or implement Iclonable interface and use Clone method. – Buddhabhushan Kamble Mar 14 '18 at 11:28
  • @BuddhabhushanKamble , serializing and de-serializing does have their own overheads. It is always debatable how fruitful it would be to afford this overhead when you have better ways to achieve the same purpose – Amit Mar 14 '18 at 11:37
  • This is indeed a duplicate. One of the answers in the duplicate question thread should suffice. I've just added [a new answer for a JSON solution](https://stackoverflow.com/a/49276795/106159) that works with types that don't implement ISerializable, but there are many other answers there you could use. – Matthew Watson Mar 14 '18 at 11:39
  • It doesn't seem to be the most popular suggestion, but I went with implementing a simple copy constructor on my object. I read the drawbacks this can lead to with code maintenance, hierarchy etc. but this object has only three properties at the moment. I put a comment in the copy constructor to review whether this solution is appropriate should more properties be introduced at a later date. – Meridian Mar 14 '18 at 12:20
  • @Meridian Actually I think that a copy constructor is a good solution. – Matthew Watson Mar 14 '18 at 13:26

1 Answers1

12

You could apply serialize-deserialize for the object to create deep copy.

public static class ObjectExtensions
{
    public static T Clone<T>(this T obj)
    {
        return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj));
    }
}

Then usage;

public void myFunction(Object original)
{
    var copyOfObject = original.Clone();
}
lucky
  • 12,734
  • 4
  • 24
  • 46