Polymorphism
Polymorphism is multiple forms of something. It can be achieved with operator overloading, method overloading, polymorphism via inheritance or polymorphism via interfaces.
Polymorphism has the ability for classes to provide different implementations of methods that are called through the same name. It allows you to invoke methods of derived class through base class reference during runtime.
It can happen with method overloading or method overriding.
Overloading – compile time
It is an early binding where methods with same name perform different tasks with different parameters but the return type should be same.
Overriding – runtime
It is a late binding approach using inheritance and virtual functions. Change the behavior of the method for the derived class.
Overloading Example:
namespace Rextester { public class Program { public static void Main(string[] args) { Test a = new Test(); string name = "Jacinta"; a.Foo(name); a.Foo(22,56.6f); } } public class Test { public void Foo(string name) { Console.WriteLine("Your name is:{0}", name); } public void Foo(int age, float mark) { Console.WriteLine("Your age is:{0} and mark is: {1}", age,mark); } } }
Overriding Example:
Class A is the base class, Class B inherits Class A. The method declared in the base class A is not re-declared in Class B but Class B has full access of Foo() method.
Case 1:
namespace Rextester { public class Program { public static void Main(string[] args) { A a = new A(); a.Foo(); B b = new B(); b.Foo(); } } public class A { public void Foo() { Console.WriteLine("A::Foo()"); } } public class B : A {} }
Output:
A::Foo()
A::Foo()
Case 2:
namespace Rextester { public class Program { public static void Main(string[] args) { A a = new A(); a.Foo(); B b = new B(); b.Foo(); a = b; a.Foo(); } } public class A { public void Foo() { Console.WriteLine("A::Foo()"); } } public class B : A { public void Foo() { Console.WriteLine("B::Foo()"); } } }
Output:
A::Foo()
B::Foo()
A::Foo()
Note: If you copy derived class to base class and you want all derived class methods to be executed then you will need to explicitly declare virtual and override keyword.
Case 3:
namespace Rextester { public class Program { public static void Main(string[] args) { A a = new A(); a.Foo(); B b = new B(); b.Foo(); a = b; a.Foo(); } } public class A { public virtual void Foo() { Console.WriteLine("A::Foo()"); } } public class B : A { public override void Foo() { Console.WriteLine("B::Foo()"); } } }
Output:
A::Foo()
B::Foo()
B::Foo()