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.
List<T>in the System.Collections.Generic namespace.ArrayListis not a preferred collection type unless you are working with legacy 1.1 code.ArrayListis a loosely typed collection and it stores objects of typeobject. The(String)in(String)items[i-1]should be unnecessary though becauseConsole.WriteLinewill perform this cast for you behind the scenes by calling the object'sToString()method.