Store Classes in ArrayList

  • Thread starter Thread starter Pablo Salazar
  • Start date Start date
P

Pablo Salazar

Hi People
Few day ago, somebody sent me this code.

ArrayList al = new ArrayList();
//Insertar datos en la lista:
al.Add("Ejemplo1");
al.Add("Ejemplo2");

It can store two string in ArrayList, my question is

ArrayList can Store Classes ?

Thanks.
 
Pablo Salazar said:
Hi People
Few day ago, somebody sent me this code.

ArrayList al = new ArrayList();
//Insertar datos en la lista:
al.Add("Ejemplo1");
al.Add("Ejemplo2");

It can store two string in ArrayList, my question is

ArrayList can Store Classes ?

ArrayList al = new ArrayList();
...
al.Add("Ejemplo1");
...
al.Add(new Person("Jack", ...));
...
al.Add(new Car(NumberPlate, "Ford", ...));
...
al.Add(new Book("I Ching", ...));
...

In fact, any System.Object-derived class instance may be stored in a
System.Collections-contained collection. You can check each stored object's
type before 'extracting' it:

foreach (System.Object o in al)
{
if (o is Book)
{
Book b = (Book) o;
...
}
else if (o is Car)
{
Car c = (Car) o;
...
}
...
}

You may care to check out the relevant documentation for more details.

I hope this helps.

Anthony Borla
 
Back
Top