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.
Console.WriteLine("Method from Base Class");
Console.WriteLine("Method from Derived Class");
//base class reference variable pointing to derived class object.
Method from Derived Class
Press any key to continue . . .