C #: from medium to advance level (Method Overriding and Polymorphism)

What is Method Overriding?

To understand, we need to introduce two new keyword : virtual and override.

In the past article we create a Enemy Class and with Inheritance we have some different Classes derived from that.

I use same Class to make a simple example.

Enemy class with one method, Attack(), and two derived Classes : Ogre and Harpy.

Now, to use the same method Attack(), but with different implementation, we need to change our code and make the Attack() method virtual, like this

If now I go in Ogre Class and type override

After type override and press Space Bar, Intellisense automatically find our Attack() method, because is virtual, and if we press Enter we now have the implementation of Attack() method.

Now, if we implement it with base.Attack() it means we call the Attack Method in Enemy Class.

But if we change the implementation of Attack() method

We now have different implementation for the same method.
Incredibly powerful!

If we need, we can call the base and the new implementation, like this

And in the console we see both of methods are called.

This is what we call Polymorphism : it provides the ability to a Class to have multiple implementations with the same name.
It is one of the core principles of Object Oriented Programming after Encapsulation and Inheritance.

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!