C# Collections ArrayList

ArrayList is from the System.Collections.ArrayList class. You do not need to specify a size of the collection when you instantiate myArrayList. You use the Add method to add objects to the list. Notice that we successfully added different numbers and text. You need an Add method because you cannot use indicies ([0], [1] and so on) because none exist. Once you have added items you can use indicies and overwrite them the same way you would with arrays.
Foreach() was used to iterate through the collection. The reason that this is even possible is because of the IEnumerable interface.
myArrayList.Count would give us the number of items in the list. It was not however used in this example. With arrays you use the Length property.
Remove() and RemoveAt() methods are part of the IList interface implementation in the ArrayList class.
Removing the item with the index 0 results in all other itmes being shifted one place in the array.
ArrayList collections enable you to add several items at once with the AddRange() method. This method accepts any object with the ICollection interface, which would include regular arrays.

namespace CollectionMike {  // ArrayList
    class Program  // Chapter11/CollectionMike
    {  // using System.Collections; need this!
        static void Main(string[] args)
        {   // a simple example of how to use Collections
            ArrayList myArrayList = new ArrayList();
            int myInt = 1;
            myArrayList.Add(myInt);  myArrayList.Add(5.786);
            myArrayList.Add(3);      myArrayList.Add("hello");
            foreach(Object myObj in myArrayList)  {
                Console.WriteLine("4 objects: {0}", myObj);  }
            myArrayList.RemoveAt(1);  // removes the element at index 1
            Console.WriteLine("\nRemoving item at index 1 (second one)");
            foreach (Object myObj in myArrayList)
                Console.Write("   {0}", myObj);
            myArrayList.Remove(3);  // removes "3"
            myArrayList.Remove("hello");  // removes hello
	     myArrayList.Remove("abscent text");  // no error thrown !
            Console.WriteLine("\nRemoved the 3 and hello");
            foreach (Object myObj in myArrayList)
                Console.Write("   {0}", myObj);
            // Removes three elements starting at index 4.
            // myArrayList.RemoveRange(4, 3);

Leave a comment

Your email address will not be published. Required fields are marked *