Wednesday, September 29, 2004

Blogging on Demand

I look through my logs now and again to see if anyone's coming to my blog (and find, invariably, that nobody is!) but I think I'll start writing posts in response to some of the searches that lead people to come here. It'll be interesting for me. I've had a look through some of them, and I've learnt a couple of new things that I didn't know about before, so I think that's good!

So. Here's the first one:
"copy arraylist in vb.net" (through Yahoo)

Answer - There are two ways you can copy an ArrayList, which allow you to copy to another arraylist or to an array.

Arraylist.Clone() creates a shallow copy of the Arraylist. What this means is that although the references to objects in the array, regardless of whether they're reference types or value types, it copies the reference to the object, but not the object itself. i.e., if you have an ArrayList of controls, and you call Clone(), you'll have 2 arraylists, and 2 sets of references to the control objects on memory, but you don't create copies of the objects themselves.

The overloaded ArrayList.ToArray() copies the arraylist and all its objects to either and array of Objects or to a typed array, using ArrayList.ToArray(Type). I personally use this one quite a lot. It uses Array.Copy() to create the new array, which (rather confusingly) sometimes produces a deep copy, and sometimes a shallow copy. I use this particularly in collection properties. I generally have a private ArrayList field that contains the objects in question, but then pass an array out through the property getter. Arraylists aren't typed, as arrays are, so I don't want my calling code to be able to add objects of different types to the collection. It's just a personal thing. I don't know if it reaches into the realms of good practice, or what.

So that's my first Blog on Demand. I hope someone finds it useful. I know I did, and learnt me a bit more about ArrayLists, Cloning and copying.

No doubt I'll add more as and when they come to me.

2 comments:

Anonymous said...

Hi,
Useful information on ArrayList copying. I needed a quick solution and found it here! Nice one. Thanks for posting :)

Anonymous said...

I just thought I would add...

you have to use a CType, like this:

newArrayList=CType(alToBeCopied, ArrayList)

For anyone who needs it... :)