C# – Polymorphism

It is said that a programmer goes through three stages when learning an object oriented programming language. e first phase is when a programmer uses non – object oriented constructs ( like for if…else, switch….case ) of the object oriented programming language. The second phase is when a programmer writes classes, inherits them and creates their objects. The third phase is when a programmer uses Polymorphism to achieve late binding.

MSDN ( Microsoft Developer Network ) explanation : ” Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides.”

Using the reference of the base type for referencing the objects of child types

Before getting into the details of polymorphism, we need to understand that the reference of a base type can hold the object of a derived type. Let a class A be inherited by a class B:

class A

{

public void Method ( )

{

}

}

class B :A

{

public void MethodB ( )

{

}

}

Then it is legal to write :

A a = new B ( ) ;

Here a reference of type A is holding an object of type B. In this case we are treating the objects of type B as an object of type A ( which is quite possible as B is a sub – type of A ). Now, it is possible to write :

a.MethodA ( ) ;

But it is incorrect to write :

a.MethodB ( ) ; //error

Although we have an object of type B ( contained in the reference of type A) , we can not accesss any members of type B since the apparent type here is A and not B.

Using methods with the same name in the Base and the sub – class

In our shape class let us define a method Draw ( ) that draws a shape on the screen:

class shape

{

public void Draw ( )

{

Console.WriteLine ( ” Drawing Shape…”);

}

}

We inherit another class Circle from the Shape class, which also contains a method Draw ( ).

class Circle : Shape

{

public void Draw ( )

{

Console.writeLine ( ” Drawing Circle… “);

}

}

Here, we have the Draw ( ) method with the same signature in both the shape and the Circle classes. Now, if in our Main ( ) method , we write

static void Main ( )

{

Circle theCircle = new Circle ( ) ;

theCircle . Draw ( );

}

Leave a Reply

Your email address will not be published. Required fields are marked *