Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

Collection Classes in .net - the ArrayList

This is the second part of an article on collection classes in .net with C#.  This part covers the ArrayList.

For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512

For the next part on Generic Lists see http://www.audacs.co.uk/ViewPage.aspx?PageID=514

Ok so on to the ArrayList.  ArrayList is a class found at System.ArrayList.  It implements the following interfaces:

IList, ICollection, IEnumerable, ICloneable

It is a collection which works a bit like an array but it's size can grow and shrink as required.  Items can be added and removed easily using Add and Remove methods.

The ArrayList holds objects - ie instances of System.Object.  That way we can have an ArrayList which contains any class at all since all classes ultimatley inherit from Object.  It does also allow us to mix objects within the collection although that is not normally thought of as being the reason for designing the class this way. 

So lets have a look at an example program.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ArrayLists
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Create a new instance of an ArrayList
            ArrayList things = new ArrayList();
 
            //Create and populate some instances of the Person class
            Person dave = new Person("Dave Amour", 42);
            Person tracey = new Person("Tracey Amour", 36);
            Person sarah = new Person("Sarah Bloggs", 23);
            Person fred = new Person("Fred Smith", 27);
            Person bill = new Person("Bill Brown", 46);
 
            //Add all of the Person instances into the ArrayList
            things.Add(dave);
            things.Add(tracey);
            things.Add(sarah);
            things.Add(fred);
            things.Add(bill);
 
            //Iterate over the items in the collection and output details to screen
            for (int i = 0; i < things.Count; i++)
            {
                Console.WriteLine(((Person)things[i]).Name + " (aged " + ((Person)things[i]).Age.ToString() + ")");
            }
 
            //Writes a blank line for readability
            Console.WriteLine();
 
            //Remove fred
            things.Remove(fred);
 
            //Output that we have removed fred
            Console.WriteLine("Removed fred" +Environment.NewLine);
 
            //Iterate over the items in the collection and output details to screen
            for (int i = 0; i < things.Count; i++)
            {
                Console.WriteLine(((Person)things[i]).Name + " (aged " + ((Person)things[i]).Age.ToString() + ")");
            }
 
            //Writes a blank line for readability
            Console.WriteLine();
 
            //Remove the item at position 0
            things.RemoveAt(0);
 
            //Output that we have removed the 1st item
            Console.WriteLine("Removed 1st item" + Environment.NewLine);
 
            //Iterate over the items in the collection and output details to screen
            for (int i = 0; i < things.Count; i++)
            {
                Console.WriteLine(((Person)things[i]).Name + " (aged " + ((Person)things[i]).Age.ToString() + ")");
            }
 
            //Remove items in the range 1..2
            things.RemoveRange(1, 2);
 
            //Writes a blank line for readability
            Console.WriteLine();
 
            //Output that we have removed items in the range 1..2
            Console.WriteLine("Removed range 1-2" + Environment.NewLine);
 
            //Iterate over the items in the collection and output details to screen
            for (int i = 0; i < things.Count; i++)
            {
                Console.WriteLine(((Person)things[i]).Name + " (aged " + ((Person)things[i]).Age.ToString() + ")");
            }
 
            //Stops the console window from closing
            Console.Read();
        }
    }
 
    ///<summary>
    /// Test Person class to be added to the ArrayList for testing
    ///</summary>
    public class Person
    {
        //Constructor
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
 
        //The persons name
        public string Name
        {
            get;
           
            set;
        }
 
        //The persons age
        public int Age
        {
            get;
 
            set;
        }
    }
}
 


This program utilises a few instances of a Person class which just contains a name and age.  We create an ArrayList and add some objects to it.  We then output these to screen.  We then do some removing in various ways and output more results to screen.

So from this you can see that the ArrayList is very easy and convenient to work with.

The only real downside is that becuase it contains a collection of objects then you need to cast to your specific object to do anything useful.  That is why we have the following code which casts the objects to a Person class.

            //Iterate over the items in the collection and output details to screen
            for (int i = 0; i < things.Count; i++)
            {
                Console.WriteLine(((Person)things[i]).Name + " (aged " + ((Person)things[i]).Age.ToString() + ")");
            }


We could have used a foreach statement instead which would have done the casting for us - eg:

            foreach (Person p in things)
            {
                Console.WriteLine(p.Name + " (aged " + p.Age.ToString() + ")");
            }


However casting is still being done and this can lead to problems.  Suppose one of the objects in our ArrayList isn't of the type expected?  In that case then we could get a runtime error.  The solution to this problem lies with Generics and Generic Lists which we will look at later and really ArrayLists shouldn't be used anymore as a Generic List is preferable.  You do however need to be familliar with ArrayLists for historical purposes and legacy apps and code.

Other instance method worth being aware of include:

  • Clear
  • Clone
  • Contains
  • CopyTo
  • Sort
  • Reverse
  • ToArray

And there are a few others too but given the obselessence of the ArrayList that should be enough for us to be aware of. 

For the next part on Generic Lists see http://www.audacs.co.uk/ViewPage.aspx?PageID=514

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status