Polymorphism in c#

Polymorphism means one name of many forms. Polymorphism means one object behaving as multiple forms. Or we can say that one function behaves in different forms.so In polymorphism, we will declare methods with the same name and different parameters in the same class or methods with the same name and same parameters in different classes. Polymorphism has the ability to provide a different implementation of methods that are implemented with the same name

Types of Polymorphism in c#:-


There are two types of polymorphism exists in c#

1. Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
2. Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)


Compile Time Polymorphism

Compile-time polymorphism means we will declare methods with the same name but different signatures

Example:-1

public class testClass
{
  public void fnNumbersAdd(int a, int b)
  {
    Console.WriteLine(a + b);
  }
  public void fnNumbersAdd(int a, int b, int c, int d)
  {
    Console.WriteLine(a + b + c + d);
  }
}


Run Time Polymorphism

Run time polymorphism or method overriding means the same method names with the same signatures. in method overriding we can override a method in base class by creating a similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.


Example :-2


public class TestBaseclass
{
  public virtual void FnSampleFunction1()
  {
    Console.WriteLine("Base Class");
  }
}

// Derived Class
public class ChildClass : TestBaseclass
{
  public override void FnSampleFunction1()
  {
    Console.WriteLine("Derived Class");
  }
}



class Program
{
  static void Main(string[] args)
  {
    // calling the overriden method of child class
    ChildClass objDc = new ChildClass();
    objDc.FnSampleFunction1();

    // calling the method from base class
    TestBaseclass objBc = new ChildClass();
    objBc.FnSampleFunction1();
  }
}






























Difference between Method Overriding and Method hiding

Method overriding allows a subclass to provide a specific implementation of a method that is already provided by the base class. The implementation in the subclass overrides (replaces) the implementation in the base class. The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.