Static and Dynamic Polymorphism in c#
This post is about one of the four pillars of OOP i.e. polymorphism in Object Oriented Programming that i am gonna explain via C#.
If you search the meaning of polymorphism then it says, "the condition of occurring in several different forms" i.e. having same name but different behavior. If we consider our daily life event then we can give many example for polymorphism few of them are as
Example 1:
Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the office.
Example 2:
Your mobile phone, one name but many forms:
- As phone
- As camera
- As mp3 player
- As radio
So as per as programming is considered then any methods or properties have same name and performing different action we can say polymorphism is achieved. There are two types of polymorhism in c#
1.Static or compile time polymorphism
2.Dynamic or runtime polymorphism
Static or Compile time Polymorphism:
In this type as name suggest the decision of behavior is made at compile time that means compiler knows which method is going to get called during the compile time only. We achieve static polymorphism by using method overloading. Method overloading is nothing but class with more than one method with the same name but different parameters. Compiler checks the type and number of parameters passed on to the method and decides which method to call at compile time and it will give an error if there are no methods that match the method signature of the method that is called at compile time.Example
In following example compiler already knows that Line 2 is going to call Add with two string parameters and Line 3 will call Add with two int parameters
class Program
{
public class Test
{
public void Add(string a1, string a2)
{
Console.WriteLine("Adding Strings :" + a1 + a2);
}
public void Add(int a1, int a2)
{
Console.WriteLine("Adding Integers :" + a1 + a2);
}
}
static void Main(string[] args)
{
Test obj = new Test();// Line 1
obj.Add("Manish " , "Agrahari");//Line 2
obj.Add(5, 10);//Line 3
}
}
1 comments:
Thanks for your Feedback !!!