sunshine



What is Polymorphism

Basically polymorphism is the phenomenon of something existing in different forms. For example water can exist as ice or steam. So they are polymorphic to water. Polymorphism is the third pillar of OOP, Encapsulation and Inheritance being first and second pillars.

So what is polymorphism?

In C#(in object oriented world) an object may be treated as the type of another object; provided the first object is derived from the second object respectively ( first object is of derived class and second object is of base class). So the first object is polymorphic to second object. The base class will have virtual methods which can be overridden in derived class for the customization needed.

A simple example would be a Shape class. Shape class can have a virtual method to calculate area. Rectangle and Triangle can derive from Shape and override the area method and implement their own version.(Please note the code below is not complete.)

public class Shape

 {

       public virtual  float Area()

       {

           return 0.0;

       }

 }

public  class Rectangle : Shape

{

    public  override float Area()

    {

            Return length * width;

    }

}

public class Circle : Shape

{

    Public  override float Area()

    {

            Return 3.14 * Radius;

    }

}



Shape  rect = new Rectangle();  //Rectangle is polymorphic to Shape

float area = Rect.Area();

Shape  circ =  new Circle() ; //Circle is polymorphic to Shape

Circ.Area() ;

As you can see Shape can take any of the derived type. OK! What is the big deal? How does it help anyway?

You can work with a group of related objects in a uniform way, which simplifies the coding. If your problem at hand is to hold several triangles , rectangles, circles and others shapes in a program and calculate their areas, one way is have a class for each shape and then keep as much arrays and iterate through them.

A much better way is to have a Size array, add every different shape into that and call the Area method. That simplifies the task tremendously.

If you are a beginner on object oriented programming, this is one vital concept you need to understand! A detailed example is provided on this site on polymorphism

Read Microsoft's explanation of polymorphism.

Grady Booche's Object Oriented Analysis and Design With Applications is great book on OOP.

We offer one on one C# training,SQL training,WCF training,WPF training,WinForms training, MVC training, ASP.NET training, Ajax & Javascript training. Please see the contacts page