Polymorphism means having many forms. The word “poly” means many and “morphs” means form. Polymorphism is one of the core principles of object-oriented programming which means it is the way of performing some task in many ways.
With polymorphism, a class can have multiple implementations with the same name.
There are two types of polymorphism in C#:
- Compile-time Polymorphism or Static (or early) Polymorphism.
- Runtime Polymorphism or Dynamic (or late) Polymorphism.
C# Compile Time Polymorphism
In this type of program, the flow of control is decided at compile time itself. It is achieved by function overloading and operator overloading. It is also known as static or early binding.
Let us go through function overloading and we will cover operator overloading in the next tutorial.
Function Overloading
A function is said to be overloaded if two or more functions having the same name but different parameters. The difference could be in a number of parameters or types of parameters so that compiler can tell the difference.
Also, while calling this function make sure to give the proper parameters according to the required called function. Learn more on method overloading in C#.
Example of C# program for function overloading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | using System; namespace Program { class PolyExample { void display(String name, int roll) { Console.WriteLine("Name: {0} Roll: {1}", name, roll); } void display(int counter) { Console.WriteLine("Value of counter: {0}", counter + 1); } //Main function static void Main(string[] args) { PolyExample obj = new PolyExample(); // Call functions obj.display("John Mac", 18); obj.display(99); } } } |
Output:
Name: John Mac Roll: 18
Value of counter: 100
C# Run Time Polymorphism
In run time polymorphism, the program is called at the time of execution that is at rum time. It is also known as the late binding or dynamic binding.
This type of polymorphism is achieved by Method Overriding.
Method Overriding
Method overriding is done through inheritance, it allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden. There is a use of the virtual keyword and override keyword as shown in the program below.
And the decision made to call the required function is done at the run time. Hence, the Runtime polymorphism.
Example: C# program for method overriding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | using System; namespace Program { public class Animal { public virtual void sleep() { Console.WriteLine("Animals Sleeps"); } } public class Dog: Animal //inheriting Animal class { public override void sleep() { Console.WriteLine("Dog Sleeps"); } } public class PolymorphismMain { public static void Main() { Animal obj = new Dog(); obj.sleep(); obj = new Animal(); obj.sleep(); } } } |
Output:
Dog Sleeps
Animals Sleeps