ArrayList deep/shallow copy question

C

Cybertof

Hello,

Can someone explain me what is the differences between these 2 lines of
code :

MyArrayList2 = MyArrayList;
MyArrayList2 = MyArrayList.Clone();

MyArrayList/MyArrayList2 are aray lists of class objects implementing
the CompareTo() method, so the list is sortable.

What happens if i make this call : MyArrayList2.Sort() ?

Will MyArrayList be sorted too ?


Regards,
Cybertof.
 
N

Nicholas Paldino [.NET/C# MVP]

Cybertof,

Here are the differences:

MyArrayList2 = MyArrayList;

This will just copy the reference to MyArrayList into MyArrayList2. If
you add an element to MyArrayList2, then you will see that in MyArrayList,
because they both point to the same thing.

MyArrayList2 = MyArrayList.Clone();

This will create a shallow copy of the ArrayList. If the elements are a
reference, then those references are copied. If they are value types, then
that is copied to the new array list. Now, if they are all reference types,
then the two array lists are pointing to the same objects. However, if you
add a new item to MyArrayList2, then it will not be shown in MyArrayList,
because MyArrayList2 is a new object, not a reference to the same
MyArrayList.

Hope this helps.
 
J

Jon Skeet [C# MVP]

Cybertof said:
Can someone explain me what is the differences between these 2 lines of
code :

MyArrayList2 = MyArrayList;

This makes the variable MyArrayList2 have the same value as MyArrayList
- in other words, they will both be references to the same object.
MyArrayList2 = MyArrayList.Clone();

This creates a *new* ArrayList which is a duplicate of the first list.
MyArrayList/MyArrayList2 are aray lists of class objects implementing
the CompareTo() method, so the list is sortable.

What happens if i make this call : MyArrayList2.Sort() ?

Will MyArrayList be sorted too ?

No. They are separate lists (you can remove things from one without it
affecting the others) - but the references *within* the lists haven't
been cloned, so if (say) the first element of MyArrayList is a
reference to a StringBuilder, and you append some text in that
StringBuilder, that append operation will be visible through the first
element of MyArrayList2 as they're both references to the same object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top