Pages

Sunday, May 12, 2013

Polymorphism in c#

Def:
Polymorphism means having more than one form. Overloading and overriding are used to implement polymorphism.

Polymorphism is of two types:

  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding

Polymorphism provides following features: 
  • It allows you to invoke methods of derived class through base class reference during runtime.
  • It has the ability for classes to provide different implementations of methods that are called through the same name.  

          Compile Time Polymorphism :

    •     Compile time polymorphism is method and operators overloading. It is also called early binding.
     
    • In method overloading method performs the different task at the different input parameters.

    Runtime Time Polymorphism :

    • Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
     
    • When overriding a method, you change the behavior of the method for the derived class.  Overloading a method simply involves having another method with the same prototype.
     
      • Note: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.    

      Sample code:(overloading)

       public partial class Overloading : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
             {
              A a = new A();      
              int r = a.m(10, 6); 
              Response.Write(r);
              }
      }

      public class A
      {
          public int m(int x, int y)
          {
              return x + y;
          }
          public int m(string x, int y)
          {
              return Convert.ToInt32(x)+ y;
          }
      }


       

      Runtime polymorphism/Overriding:

      { this topic discuss another post(virtual and overridding)} 

      Note: Bec few propertes need to impliment this topic(upcasting,downcasting,...) 

No comments:

Post a Comment