C# Classes Theory Part 4 Polymorphism Part 3

Here is an example of polymorphism using our familiar Animal and Cow classes.

using static System.Console;
namespace Polymorphism3
{   // Code written by Mike and adopted from book
    // C# A Beginner's Tutorial - Chapter 11.
    class Program
        static void Main(string[] args)
            Animal animal;
            animal = new Cow();
            // output of line below: Polymorphism3.Cow
            // output of line below: I am a cow
            // the line above is Polymorphism in action
            Cow cow = (Cow)animal;
            // output of line below: I am Mooing
    class Animal  {
        public virtual void Work()  {
            WriteLine("I am an animal");
    class Cow : Animal  {  // inherits from animal
        public override void Work()  {
            WriteLine("I am a cow");
        public void Moo()  {
            WriteLine("I am Mooing");

Leave a comment

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