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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    class Student
    {
        //marked virtual
        public virtual void PrintName()
        {
            Console.WriteLine("Method from Base Class");
        }
    }

    class Student1 : Student
    {   
        //overriden
        public override void PrintName()
       {
           Console.WriteLine("Method from Derived Class");
       }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //base class reference variable pointing to derived class object.
            Student S1 = new Student1();
            S1.PrintName();
        }
    }
}

 Output:

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