Introduction to Polymorphism in C#
Hello friends, I hope you all are having fun. In today's tutorial, we will have a look at
Introduction to Polymorphism in C#. It's our 16th tutorial in C# series and polymorphism is considered as a main pillar of object oriented programming.
In our previous tutorial, we have seen a detailed
Introduction to Inheritance in C# and along with it, we have also discussed How to hide a Method in Parent Class, if the same method exists in Child class. This Method Hiding is actually the basis of Polymorphism, so let's discuss it out in detail:
Introduction to Polymorphism in C#
- Polymorphism in C# enables the user to invoke a Child Class Method & override the Parent Class Method, using a Parent Class Reference variable.
- In our previous lecture on Inheritance, we have also discussed method hiding and our last code is shown in below figure:
- In the above code, you can see that we have used method hiding by using new keyword with ChildClass Method.
- So, now instead of hiding the method let's override it and have a look at the results:
- In the above figure, you can see that I have used virtual keyword with Parent Class Method.
- Moreover, instead of new keyword, I have used override keyword with Child Class Method.
- I have used the same reference variables as I did for Method Hiding code, but here in the third case, the child class method is called.
- So, in Polymorphism, if the Child Class is involved in reference variable, then it will always override the Parent Class Method and will use the Child Class Method.
- So, we can say that if we want to completely override any function in Parent Class, then we need to add virtual keyword in its definition.
- This virtual Parent Class Method will always get override by any Base Class Method, which has the same name and has override keyword in its definition.
- But if we want to invoke the virtual Parent Class Method, then we have to use Parent Class reference variable.
- So, this third variable PC2 is the main difference between Method Hiding & Method Overriding (Polymorphism).
So, that was all about Polymorphism in C# and if you have got the Method Hiding then it won't be much of an issue for you. In the next lecture, we will have a look at Introduction to Structures in C#. Till then take care & have fun !!! :)