Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a copy of an object?

Tags:

c#

asp.net

I created a class called Colors. I am setting certain properties on the Colors object and setting it in a Session variable. When I access the Session variable on another page, I am noticing that if I change properties on objColors below, it changes the Session and does not keep the original properties which is what I want it to do. Here is an example:

Session["Colors"] = Colors;

Colors objColors = Session["Colors"];

//If I change objColors, it changes the Session.  I don't want this to happen.

Is there a better way to keep retain the original properties? Why does it do this?

like image 457
Xaisoft Avatar asked Mar 10 '09 21:03

Xaisoft


People also ask

How do you copy an object to another object?

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.

How do you make a copy of an object in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.


2 Answers

Create a copy constructor for Colors. Then, do this.

Colors objColors = new Colors((Colors)Session["Colors"]);

In your new constructor, just copy the values that you need to and do your other constructor-related things.

What's happening in your code is that you are getting a pointer to a Colors object. Session["Colors"] and objColors point to the same object in memory, so when you modify one, changes are reflected in both. You want a brand spankin' new Colors object, with values initialized from objColors or Session["Colors"].

edit: A copy constructor might look like this:

public Colors(Colors otherColors)
{
    this.privateVar1 = otherColors.privateVar1;
    this.publicVar2 = otherColors.publicVar2;
    this.Init();
}
like image 156
Samantha Branham Avatar answered Sep 25 '22 17:09

Samantha Branham


You can implement your own cloning methods to make a "copy" of an object. The reason this is happening is because the assignment of Colors objColors = Session["Colors"]; is a reference assignment, this is by design. All you are doing is making a local scope reference to an object that already exists. Take a look at IClonable for actual object cloning. This isn't necessary either you can implement your own copy methods. You may also want to take a look at MemberwiseClone depending on how deep your object goes.

like image 27
Quintin Robinson Avatar answered Sep 23 '22 17:09

Quintin Robinson