vijay

welcome Netizen

welcome Netizen
Hi folks this site Share Basic Knowledge in .NET, DotNet, C#,DOT NET CODE, ASP.NET, VB.NET, DOT NET TRICKS,Dotnetcode,Android and Latest Technology Articles in VB,Android and ASP.NET

Monday, January 21, 2013

Polymorphism in C#



Introduction
Polymorphism 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
 public int add(int a, int b)
    {
        return a + b;
    }

    public string add(string a, string b)
    {
        return a + b;
    }
//this will not work
public int mult(int a, int b)
    {
        return a * b;
    }

    public double 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:
public class BClass
    {
        public virtual int  Add(int a,int b) {
            return a + b;
        }
   
    }
    public class DClass : BClass
    {
        public override int  Add(int a, int b)
        {
            return a + b + a;
        }
      
    }
///////////////////////////////////
//Calling method
BClass b = new BClass();
       Response .Write ( b.Add(4, 5));
        b = new DClass();
       Response .Write (b.Add(3, 4));

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

0 comments:

Post a Comment