Get a copy (not a reference) of a class

  • Thread starter Thread starter ~toki
  • Start date Start date
T

~toki

I have a class with a custom property called Name = "pepe"

When i create a copy of it (Pepe pepe = oldpepe;)

And change the property of the 'new' class (pepe.Name = "pepe1")
oldpepe.Name has canged to "pepe1"

How can i prevent that oldpepe="pepe" changes?
 
~toki said:
I have a class with a custom property called Name = "pepe"

When i create a copy of it (Pepe pepe = oldpepe;)

And change the property of the 'new' class (pepe.Name = "pepe1")
oldpepe.Name has canged to "pepe1"

How can i prevent that oldpepe="pepe" changes?


Hi ~toki,

You can implement the IClonable interface and then call Clone() when you
want a copy.

Joe
 
I would make a copy constructor and a Clone() method

/* can be private or protected */
public Pepe(Pepe p)
{
// Assign this fields here using fields from p
}

public Pepe Clone()
{
return new Pepe(this);
}



HTH
Brian W
 
~toki said:
I have a class with a custom property called Name = "pepe"

When i create a copy of it (Pepe pepe = oldpepe;)

And change the property of the 'new' class (pepe.Name = "pepe1")
oldpepe.Name has canged to "pepe1"

How can i prevent that oldpepe="pepe" changes?

Hi,

You're not making a copy of it when you're setting pepe to reference
oldpepe. It's still just one object with two references to it. You should
make the Pepe class implement the ICloneable interface, which means you need
to write something like:

class Pepe : ICloneable
{
public Object Clone()
{
return MemberwiseClone();
}
}

MemberwiseClone is a protected method which all objects inherit from
System.Object.
Now you can write code like:

Pepe pepe = (Pepe) oldpepe;
pepe.Name = "pepe1";
Console.WriteLine(pepe.Name); // Outputs "pepe1"
Console.WriteLine(oldpepe.Name); // Outputs "pepe"

Note that even this only creates a shallow copy of your object. That is, if
you have any references to other objects within Pepe, those objects will be
shared. If you want deep copy, you need to implement that yourself.

Regards,
Einar
 
Back
Top