Use this space to put some text. Update this text in HTML

468x60 banner ad

Advertise with Us

Powered by Blogger.
Showing posts with label Polymorphism in C-Sharp. Show all posts
Showing posts with label Polymorphism in C-Sharp. Show all posts

Tuesday 1 March 2016

Polymorphism in C-Sharp


1. In Polymorphism poly means “multiple” and morph means “forms” that means many forms.
2. In polymorphism we will declare methods with same name and different parameters in same class.
3. or methods with same name and same parameters in different classes.
In Polymorphism we have 2 different types those are
     -      Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
     -      Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)

Compile Time Polymorphism or Early Binding

Compile time polymorphism means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method overloading.
Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)
Example


public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but having different input parameters this is called method overloading or compile time polymorphism or early binding. 

Run Time Polymorphism or Late Binding

Run time polymorphism also called as late binding or method overriding or dynamic polymorphism.
Run time polymorphism or method overriding means same method names with same signatures.
In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.
Example




public class clsShape
    {
        public int _radius = 5;
        public virtual double getArea()
        {
            return 0;
        }
    }
    public class clsCircle : clsShape
    {
        public override double getArea()
        {
            return 3.14 * _radius * _radius;
        }
    }
    public class clsSphere : clsShape
    {
        public override double getArea()
        {
            return 4 * 3.14 * _radius * _radius;
        }
    }




As you can see from above code that we have one base class "clsShape" with a "virtual" method "getArea()" and two derived classes "clsCircle" and "clsShape" each having an "override" method "getArea()" with different implementations.