I have a question about ArrayList (C#) and I think I know the answer but need confirmation. I would like a solid foundation of knowledge.
So here is my question:
I was looking at example of ArrayLists and came across this line of code:
for (int i=1; i<=items.Count; i++)
{Console.WriteLine("{0}. {1}", i, (String)items[i-1]);}
Here is what I think I know what’s going on.
- a for loop is executed for each item in the ArrayList.
- the code executed is a method call to the Console’s WriteLine method with a formal parameter.
- {0} will be replaced with the current value of i in the for loop and {1} will be replaced with the value in the ArrayList index of [i – 1].
- the reason for [i – 1] is because the index of an ArrayList begins at 0 and not 1.
Here is what I am unsure about.
1. (String) << this I believe is casting the value in the current ArrayList index to a String type?
2. What is the type of an ArrayList item? Is it just an object type?
The concept is a bit foggy to me and I am just looking for a bit of clarity. Thanks for any help you can spare.
Arrays and lists are 0-indexed in C#. This means that the first item is at index
0and the last item is at indexitems.Count - 1. I think your code would be clearer if your for loop started from0:The indexer of
ArrayListhas a return type ofobject, so if your list contains strings you will normally want to cast to string when you fetch an object from theArrayList. However in this specific case there’s no need to perform the cast because theWriteLineoverload you are calling has the signaturevoid WriteLine(string, object, object). It’s fine to just pass anobjectto this method. Internally theWriteLinemethod will callToStringon your object.You should also consider using the generic
List<T>class instead ofArrayList. TheArrayListclass was useful when .NET was first released, but new code in .NET 2.0 or above should prefer to useList<T>.