Wednesday 10 August 2011

Polymorphism in C sharp

Polymorphism in C sharp:

The word Polymorphism means MANY FORMS.
Ability to show more than one form.

Polymorphism is of  TWO types;
1. Complietime polymorphism (nothing but Method Overloading)
    In Method Overloading method takes different input parameters and it do different tasks.
    It's also called early binding.
Example:

class Program

    {

        public class ShapeInformation

        {

            public void Area(float r) // With 1 parameter
            {

                float a = (float)3.14 * r;
                Console.WriteLine("Area of a circle:",a);
            }

            public void Area(float l, float b) // With 2 parameters
            {

                float x = (float)l* b;
                Console.WriteLine("Area of a rectangle: {0}",x);
            }

            public void Area(float a, float b, float c) //3 parameters
            {
                float s = (float)(a*b*c)/2;
                Console.WriteLine("Area of a circle: {0}", s);
            }

        }



        static void Main(string[] args)
        {

            ShapeInformation SI = new ShapeInformation();

            SI.Area(2.0f);
            SI.Area(20.0f,30.0f);
            SI.Area(2.0f,3.0f,4.0f);
            Console.ReadLine();
        }

    }

Note:
        While method overloading overloads must be in different signature,
         name is same and the number of parameters should be varies.

2. Runtime polymorphism (nothing but Method Overriding)
    It's Done using in inheritance and virtual functions. Mthod overriding is called Runtime polymorphism
    It's also called late binding.
    when child class declares a method that has the same type arguments as a method declared by one of its baseclass
Example:
public class ParentObject
{
    public virtual void Draw()
    {
    Console.WriteLine("I am a drawing object:Parent.");
    }
}
public class Child: ParentObject
{
    public override void Draw() //Draw is a base class name overriding in child class
    {
    Console.WriteLine("I am a Triangle:Child.");
    }
}


public class ShapeDemo
{
    public static void Main()
    {
    ParentObject ParentObj = new child();
    ParentObj.Draw();
   
}

No comments:

Post a Comment