8

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?

8
  • stackoverflow.com/questions/78536/deep-cloning-objects?rq=1 Commented Mar 14, 2018 at 11:20
  • better you use copy constructor, that would be much in your control. Commented Mar 14, 2018 at 11:21
  • Indeed, smells like closing Commented Mar 14, 2018 at 11:22
  • You can serialize and deserialize your object. You will get another object or implement Iclonable interface and use Clone method. Commented Mar 14, 2018 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 Commented Mar 14, 2018 at 11:37

1 Answer 1

16

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

using Newtonsoft.Json;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.