Stage 5: Polymorphic code

Stage 5: Polymorphic code

Highlights:

  • From the previous stage the code will be modified to be polymorphic

  • Objects are created in a different order to simulate fetching from a database or service

  • All objects adhere to the required specifications

  • Polymorphism and inheritance are used to treat all objects as similar types

  • Collection initialization syntax is used to create anonymous objects

  • Advanced for loop is used to iterate over the collection

  • Type casting is used to access specific methods for different object types

  • Interfaces and base classes can be used as types to make the code more uniform and manageable

Animal.cs

No change!

Bird.cs

No change!

Cat.cs

No change!

Dog.cs

No change!

Eagle.cs

No change!

ISingable.cs

No change!

Parrot.cs

No change!

Program.cs

using MyApplication.Animals;

Animal[] animals = [
     new Eagle("Jack"),
     new Dog("Mike"),
     new Cat("Tom"),     
     new Parrot("Glory"),     
];

foreach (Animal animal in animals)
{
    Console.WriteLine($"{animal.Name} created!");

    animal.Eat();
    animal.Climb();    

    if(animal is Bird b)
      b.Fly();
    
    if(animal is ISingable s)
        s.Sing();
    Console.WriteLine();
}

Last updated