Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 652
  • Last Modified:

clone - shallow and deep copy?

hi
how would I use clone on an arraylist?
is it just
arraylist al = new arraylist();
alcloned = al.clone();

Also if this is a cloned / shallow copy how do I perform a deep copy?

Thanks
Paul
0
paulwhelan
Asked:
paulwhelan
  • 2
1 Solution
 
rinksno1Commented:
using the copy...method
0
 
paulwhelanAuthor Commented:
Ok I see I can do

al.copyto
and
al.clone

So what would be examples using the two of them?

And is copyto 'deep' and clone 'shallow'?

thanks
Paul
0
 
paulwhelanAuthor Commented:
Is it like this?

            ArrayList al2 = al.Clone();
            ArrayList al3 = new ArrayList();
            al.CopyTo(al3);
0
 
neilpriceCommented:
Hi,

Clone just creates a shallow copy.  This means for every reference type variable stored in the arraylist, the new arraylist will simply have a reference to the same piece of information.  CopyTo takes the ArrayList and copies some or all of it to a one dimensional array.

You can try iterating over the ArrayList and populating a new one with new versions of each object as you go along.  This would of course be a lot easier if you know the data types that are being stored in the ArrayList in the first place.

There is no general deep copy functionality in .NET for ArrayList as far as I am aware.  In fact, for an ArrayList, the Clone method seems to be somewhat broken in this regard since implementing the IClonable interface (and hence Clone) is meant to (and I quote from MSDN) "to support cloning beyond that supplied by MemberwiseClone." which it clearly doesn't in this case just providing another shallow copy.

Serialization idea taken from:
http://www.dotnet4all.com/dotnet-code/2004/10/how-to-deep-copy-of-arraylist.html

If the classes inside the arraylist are serializable you can do the following: (adapted from the above website)

"
..
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
..

ArrayList a = new ArrayList();
ArrayList b = new ArrayList();

.. // populate a here with value types and serializable classes

MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(ms, a);
ms.Seek(0,SeekOrigin.Begin);
b = (ArrayList)bf.Deserialize(ms); // ArrayList b now has an independent copy of everything from a
"

Hope this helps,
Neil
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now