Xaisoft Xaisoft - 11 months ago 66
C# Question

How do you make a copy of an object?

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?

Answer Source

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;