Re: MemberwiseClone() doesn't like arrays?



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>

.



Relevant Pages

  • Re: [General]acces of members of subclass
    ... public class My_Class { ... How can I access public members w and z once I have done this: ...
    (comp.lang.java.help)
  • Re: NullReferenceException when passing structures by reference to a C API
    ... to isolate the problem you may comment out some members of ADMIN_PROF struct ... public struct ADMIN_PROF ... public String login_name; ... public int warning_flag; ...
    (microsoft.public.dotnet.framework.interop)
  • Re: refactoring (base vs child)
    ... will be childeren of this class but memebers from base class will now be ... refer to base which doesn't have those members anymore (because they are ... abstract class MyOldBaseClass { ... override public String DoStuff{... ...
    (microsoft.public.dotnet.languages.csharp)
  • Reflection - How to retrieve a members name?
    ... Say I have an ArrayList of objects that contains references to members ... public string PrintMembersNames() ...
    (microsoft.public.dotnet.languages.csharp)

Loading