Re: MemberwiseClone() doesn't like arrays?
- From: Xiasma <Xiasma@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Mon, 10 Mar 2008 02:52:16 -0700
Marc,
The problem isn't quite that simple: when I call MemberwiseClone() from my
inherited ArrayList, there seems to be some private member which actually
holds the items in the array which is shallow copied, so changing the
contents of the arraylist inthe clone also changes the contents in the
original.
Take a look at the code below for a demonstration.
I have a class thinglist which contains various members (in this case, a
string called Text). When I clone my thinglist, I can change the members on
the new thinglist and that, as expected, doesn't affect my original.
However, if I were to call clonedthinglist.Clear(), the contents of my
original thinglist would also disappear.
FWIW, I'm using .Net 3.5 - a very simple console app.
<pre>
using System;
using System.Collections;
namespace ConsoleApplication3
{
public class thing
{
public string Text;
}
public class thinglist : ArrayList
{
public string Text;
public thinglist doClone()
{
return this.MemberwiseClone() as thinglist;
}
}
class Program
{
static void Main(string[] args)
{
thing th1 = new thing();
th1.Text = "th1";
thing th2 = new thing();
th1.Text = "th2";
thinglist tl1 = new thinglist();
tl1.Text = "tl1";
tl1.Add(th1);
tl1.Add(th2);
thinglist tl2 = tl1.doClone();
tl2.Text = tl2.Text + "_copy";
for(int i = 0; i < tl1.Count; i++)
{
thing newth = new thing();
newth.Text = (tl1[i] as thing).Text + "_copy";
tl2[i] = newth;
}
Console.WriteLine(tl1.Text);
foreach(thing th in tl1)
{
Console.WriteLine("tl1[]" + th.Text);
}
Console.WriteLine(tl2.Text);
foreach (thing th in tl2)
{
Console.WriteLine("tl2[]" + th.Text);
}
Console.ReadKey();
}
}
}
</pre>
.
- Follow-Ups:
- Re: MemberwiseClone() doesn't like arrays?
- From: Marc Gravell
- Re: MemberwiseClone() doesn't like arrays?
- From: Marc Gravell
- Re: MemberwiseClone() doesn't like arrays?
- From: Jon Skeet [C# MVP]
- Re: MemberwiseClone() doesn't like arrays?
- Prev by Date: Re: Settings invisible field values for user created rows in DataGridView
- Next by Date: Re: Linq across oracle, access?
- Previous by thread: Linq to xml and collections
- Next by thread: Re: MemberwiseClone() doesn't like arrays?
- Index(es):
Relevant Pages
|
Loading