We will learn about polymorphism in c# with an example and Type of polymorphism in c# in this article. That will help you understand the concepts of polymorphism in c# with real time example for fresher as well as experienced people.
What is polymorphism?
It is used to one object behaving as multiple forms. Or polymorphism means one name many forms.
Real Time Example:
1. A person behaves as an employee in the office, that the same person behaves as a father in the house, that the same person behaves as a customer in the shopping malls.
Description: a person is one object. It behaves as an employee in office as well as the father in the house. So the concept is here one name many forms.
Type of polymorphism
Type of polymorphism
- Compile time polymorphism / Static polymorphism
- Run time polymorphism / Dynamic polymorphism
- Static or Compile time polymorphism:
In the compile time polymorphism compiler know which method is going to call at compile time called compile-time or Static polymorphism.
The static or compile time polymorphism can be achieved by using “function overloading”.Where the compiler know which overloaded method is going to call at compile time.
function overloading means the same method name but the type of parameter should be different.
Example 1: This is the basic example to understand the concept of method overloading.
using System;
namespace MethodOverloading
{
class Program
{
// Method Overloading
public int Add(int x, int y)
{
return x + y;
}
public int Add(int x, int y, int z)
{
return x + y + z;
}
static void Main(string[] args)
{
Program prog = new Program();
Console.WriteLine("Addition of Number is {0}", prog.Add(10, 20));
Console.WriteLine("Addition of Number is {0}", prog.Add(10, 20, 30));
Console.ReadLine();
}
}
}