Pages

Men

rh

7/01/2012

What is mean by Polymorphism in C#

Polymorphism :-
The ability to request that same operations be performed by a wide range of different types of things. The polymorphisms is achieved by using many different techniques named
  •  Method overloading
  •  Method overriding
  •  Operator overloading 

Method Overloading:

ΓΌ    It can be defined as, ability to define a several methods all with the same name. A Function can be overloading in two situations
When data type arguments are changed.
When number of arguments are changed.        
Example:

      Public class MyLogger
   {
         Public void LogError (Exception e)
           {
           // Implementation goes here
            }
 
Public bool LogError (Exception e, string message)
{
// Implementation goes here
}
}
  
Operator Overloading:  
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

Example
public class Complex
{
    Private int real;
    Public int Real
    {
   Get {return real; } 
    }

    Private int imaginary;
    Public int Imaginary
    {
   Get {return imaginary; }
    }

    Public Complex (int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    Public static Complex operator +(Complex c1, Complex c2)
    {
        Return new Complex (c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }
}

I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.

Method Overriding:
Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass's method has to have the same name and parameter list as the super-class's overridden method.

Example:

   Class BC
   {
     public void Disp()
      {
        System.Console.WriteLine("BC:: Display");
      }
  }

Class DC :  BC
  {
      new public void Display()
      {
        System.Console.WriteLine("DC:: Display");
      }
  }
 
 Class  Demo
 {
   Public static void Main()
   {
    BC b;
    b = new BC();
   b.Disp();
  }
}

No comments :

Post a Comment