Monday, January 21, 2013

Polymorphism in C#

IntroductionPolymorphism is the one of the primary characteristics in
object oriented programming.Polymorphism is the capability of one object to behave in
multiple ways.Polymorphism is the capability of process objects differentially depending on their data types.Polymorphism is the capability to redefine the methods for
derived class.Polymorphism is achieved in two different types of way, they
are

Compile time polymorphism

Run time polymrphism

Compile
time Polymorphism

Compile time
Polymorphism also known as method overloading.

Method
overloading means having two or more methods with the same name but with
different signatures.

Method have same name and
different parameters ,so this information know compiler at the time of
compilation, an therfore the compiler is able to select the appropriate calling
method at the compile time,so this process is called as compile time polymorphism.

Note:

Method overloading concern only the parameters.But not with different retrun type.

If
you have same two function name with same parameter with different return type
it will not compile,it will show error.

Eg:

//this
will work

publicint
add(int a, int b)

{

return a + b;

}

publicstring
add(string a, string b)

{

return a + b;

}

//this
will not work

publicint
mult(int a, int b)

{

return a * b;

}

publicdouble
mult(int a, int b)

{

return a * b;

}

//it
will show error

// Type
'_Default' already defines a member called 'mult' with the same parameter
types

Run
time Polymorphism

Run
time Polymorphism also known as method overriding

Method
overriding means having two or more methods with the same name, same
signature but with different implementation.

In run-time polymorphism when calling method using class
name,it will decide the calling method at the run time,so this process is
called as run time polymorphism.

Eg:

publicclassBClass

{

publicvirtualintAdd(int a,int b)
{

return a
+ b;

}

}

publicclassDClass : BClass

{

publicoverrideintAdd(int a, int b)

{

return a
+ b + a;

}

}

///////////////////////////////////

//Calling method

BClass b
= newBClass();

Response .Write ( b.Add(4, 5));

b = newDClass();

Response .Write (b.Add(3, 4));

I hope you like this article …Please post your comments to
corret myself is there anything wrong…