C# ArrayList of Custom Objects


ArrayList of Custom Objects

namespace Ch11Ex01
{
    class Program {
        static void Main(string[] args)  {
            WriteLine("Create an ArrayList type collection of Animal " +
                          "objects and use it:");
            ArrayList animalArrayList = new ArrayList();
            Cow myCow2 = new Cow("Rual");
            animalArrayList.Add(myCow2);
            animalArrayList.Add(new Chicken("Andrea"));

            foreach (Animal myAnimal in animalArrayList)
            {
                WriteLine($"New {myAnimal.ToString()} object added to ArrayList collection," +
                             $" Name = {myAnimal.Name}");
            }  // New Ch11Ex01.Cow object added to ArrayList collection, Name = Rual
            WriteLine($"ArrayList collection contains {animalArrayList.Count} "
                + " objects.");
            ((Animal)animalArrayList[0]).Feed();
            ((Chicken)animalArrayList[1]).LayEgg();
            ReadKey();
        }
    }
}

The last two lines shown above are interesting and require some explanation. First, review polymorphism.
The ArrayList collection is a collection of System.Object objects (you have assigned Animal objects via polymorphism). This means that you must use casting for all items.

namespace Ch11Ex01  // file: Animal.cs
{
    public abstract class Animal
    {
        protected string name;
        public string Name  {
            get { return name; }
            set { name = value; }
        }
        public Animal() { name = "The animal with no name"; }
        public Animal(string newName) { name = newName; }
        public void Feed() => WriteLine($"{name} has been fed.");
    }
}
namespace Ch11Ex01  // file: Cow.cs
{
    public class Cow : Animal {
        public void Milk() => WriteLine($"{name} has been milked.");
        public Cow(string newName) : base(newName) { }
    }
}
namespace Ch11Ex01  // Chicken.cs
{
    public class Chicken : Animal {
        public void LayEgg() => WriteLine($"{name} has laid an egg.");
        public Chicken(string newName) : base(newName) { }
    }
}

Leave a comment

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