What is Method Overriding & Polymorphism in C#?

What is Method Overriding & Polymorphism in C#?
Rating: 5 - 1 Votes

What is Method Overriding & Polymorphism in C#?

What is Polymorphism in C#?

What is Polymorphism in C#?

What is Method Overriding?

In method hiding in C#.Net, we have seen how to use new keyword in derived class method to hide the base class method.  Also, we know that derived class object will always call to its own method in case of method hiding.  But if we create a base class reference variable pointing to derived class object, then base class method will be called.  Now, a question arises here, what if we want to call derived class method using base class reference variable?  For this, we make use of Method Overriding.  In Method Overriding, we basically mark the base class method as virtual using virtual keyword and then override that method in the derived class.

What is Polymorphism?

Polymorphism is a part of Method Overriding.  Polymorphism basically is calling a derived class method using base class reference variable at runtime.  Because base class method is marked as virtual, all the derived classes can override this method and there is no need to use new keyword in this case.  An example of Polymorphism in C# is given below.

 Output:

Method from Derived Class
Press any key to continue . . .