When you have the explicit array (string[]), anytime you pull an item out
of the array, ex:
string s = x[0];
you (and the compiler) can safely assume that x[0] is actually a string.
ArrayList on the other hand holds "System.Object" - basically ANY type.
Thus, to retrieve an item, you would need to cast it. There are a couple
ways to do this:
string s = (string)x[0];
string s = x[0] as string;
The first will throw an InvalidCastException in the event that x[0] is NOT
a string, so use it only if you are 100% completely positive the list only
holds strings. The second will simply return a 'null' instead of throwing
an exception.
Also - a string[] is a fixed size array. Once the array is created, you
cannot add new items, or remove items. With ArrayList, it dynamically
adjusts the size, so you can add/remove items as you wish.
In .NET 2.0, with the introduction of generics, you can use List<string>
(or List<int> or List<SomeObj> -- whatever you need). This is the
equivalent of ArrayList (in terms of being able to add/remove items) with
the added advantage of not needing to cast items out of it.
--
Adam Clauss
Martin Arvidsson said:
Hi all you gurus!
Whats the biggest difference between using a string[] x; or an ArrayList
x;
When to use wich?
Regards
Martin