top of page

C# Tutorial For Beginners: Polymorphism

Updated: Jan 18, 2022

Polymorphism means that we can use class fields and methods and use them in another form in a class that inherits from it. For example, we can use Polymorphism to take a base method and change its form when inheriting it from a different class.


class Animal //Top_level Class

{

public void animalSound()

{

Console.WriteLine("The animal sound is....");

}

}


class Lion:Animal

{

public void animalSound()

{

Console.WriteLine("The animal sound is Rrrrrr");

}

}


class Cow:Animal

{

public void animalSound()

{

Console.WriteLine("The animal sound is Mooooo");

}

}


class Program

{

static void Main(string[] args)

{

//Create an object per class and call the animalSound method

Animal Animal_Base_Class = new Animal();

Animal lion_inherits_Class = new Lion();

Animal cow_inherits_Class = new Cow();


//Access the animalSound method per class

Animal_Base_Class.animalSound();

lion_inherits_Class.animalSound();

cow_inherits_Class.animalSound();

}

}


Result:

The animal sound is....

The animal sound is....

The animal sound is....


As you can see, the outcome from the example above was not the one that was expected. The root class method overrides the derived class method when they have the same name.


To block the override scenario, we can use the ‘virtual’ keyword in the root class and the override keyword for each derived class. Let's check it with the same code above:


class Animal //Top_level Class

{

public virtual void animalSound()

{

Console.WriteLine("The animal sound is....");

}

}


class Lion:Animal

{

public override void animalSound()

{

Console.WriteLine("The animal sound is Rrrrrr");

}

}


class Cow:Animal

{

public override void animalSound()

{

Console.WriteLine("The animal sound is Mooooo");

}

}


class Program

{

static void Main(string[] args)

{

//Create an object per class and call the animalSound method

Animal Animal_Base_Class = new Animal();

Animal lion_inherits_Class = new Lion();

Animal cow_inherits_Class = new Cow();


//Access the animalSound method per class

Animal_Base_Class.animalSound();

lion_inherits_Class.animalSound();

cow_inherits_Class.animalSound();

}

}


Result

The animal sound is....

The animal sound is Rrrrrr

The animal sound is Mooooo




131 views0 comments