P
pinkfloydfan
Hi all
I have a class that implements the ICloneable interface whereby the
Clone() method returns MemberwiseClone().
One of the elements of the class is an array and although the Clone
method appears to work, if I call a method that then adjusts the
members of that array on the new class, the original class is also
adjusted.
Does anyone know why this is the case and how to avoid it?
An simple example of this in action can be seen from the code is
below:
public class TestClone : ICloneable
{
private int[] data;
public int[] Data
{
get { return data; }
set { data = value; }
}
public TestClone() { }
public TestClone(int[] _data) { data = _data; }
public void AdjustData(int adjuster)
{
int nb=0;
foreach (int qq in Data)
{
this.Data[nb] += adjuster;
nb++;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
class Program
{
static void Main(string[] args)
{
int[] testdata = {3,1};
TestClone test1 = new TestClone(testdata);
TestClone test2 = new TestClone();
test2 = (TestClone)test1.Clone();
test2.AdjustData(3);
Console.WriteLine("test1 value is {0}, test2 value is
{1}", test1.Data[0], test2.Data[0]);
Console.ReadLine();
}
}
The output of this is:
test1 value is 6, test2 value is 6
It should be:
test1 value is 3, test2 value is 6
I have a class that implements the ICloneable interface whereby the
Clone() method returns MemberwiseClone().
One of the elements of the class is an array and although the Clone
method appears to work, if I call a method that then adjusts the
members of that array on the new class, the original class is also
adjusted.
Does anyone know why this is the case and how to avoid it?
An simple example of this in action can be seen from the code is
below:
public class TestClone : ICloneable
{
private int[] data;
public int[] Data
{
get { return data; }
set { data = value; }
}
public TestClone() { }
public TestClone(int[] _data) { data = _data; }
public void AdjustData(int adjuster)
{
int nb=0;
foreach (int qq in Data)
{
this.Data[nb] += adjuster;
nb++;
}
}
public object Clone()
{
return MemberwiseClone();
}
}
class Program
{
static void Main(string[] args)
{
int[] testdata = {3,1};
TestClone test1 = new TestClone(testdata);
TestClone test2 = new TestClone();
test2 = (TestClone)test1.Clone();
test2.AdjustData(3);
Console.WriteLine("test1 value is {0}, test2 value is
{1}", test1.Data[0], test2.Data[0]);
Console.ReadLine();
}
}
The output of this is:
test1 value is 6, test2 value is 6
It should be:
test1 value is 3, test2 value is 6