Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Copy of Object Without Reference To Original [duplicate]

Tags:

c#

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?

like image 571
Meridian Avatar asked Mar 14 '18 11:03

Meridian


People also ask

How do you copy an object by value not by reference?

assign() method is used to copy all enumerable values from a source object to the target object. Example: const obj = {a:1,b:2,c:3}; const clone = Object. assign({},obj); console.

How do you avoid reference copy in TypeScript?

So everyone needs to copy an object into another variable but we don't need to reference it, we need to create a new object from the copying object. So, on JavaScript & TypeScript languages, we have the option to do that in multiple ways. But we have used the “newObject = {… Object}” thing commonly in typescript.

Can you copy an object with object assign?

The Object. assign() method can be used to merge two objects and copy the result to a new target. Just like the spread operator, If the source objects have the same property name, the latter object will replace the preceding object. Now, let's look at another example of merging in Typescript.


1 Answers

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();
}
like image 78
lucky Avatar answered Oct 18 '22 00:10

lucky