«

»

Sep 19

Polymorphism in csharp

Polymorphism means many form, Polymorphism play major role in object oriented programming. They are static and dynamic.

Static Polymorphism : Method overloading and operator overloading are static polymorphism. In static polymorphism, the decision and response to a method is determined at the compile time. Static polymorphism involves static binding or early binding. Hence, calling of method should be done in compile time only. Method overloading or function overloading is the concept of having more than one methods in a class with the same name and different parameters.

Example :

Class myname{
Public void myfunction(int x, int y)
{
Console.writeline(“Integers = ”+x+y);
}
Public void myfunction(char x, char y)
{
Console.writeline(“Characters = ”+x+y);
}
}

Above Example code have two function with same name but different parameter. Function execute according to parameter. If assign int parameter then execute first function and assign char parameter then execute second function.

Dynamic Polymorphism : method Overriding and virtual function are dynamic Polymorphism. In Dynamic Polymorphism,  the decision and response to a method is determined at the run time. dynamic polymorphism involves late binding. Method overriding or function overriding is the concept of having duplicated methods in base and derived classes with same name as well as same parameters.

Cases of Method Overriden

  1. Only abstract and virtual methods can be overridden.
  2. We cannot declare an abstract method without an abstract class.
  3. And we cannot an instance of an abstract class.
  4. For more information, read abstract and virtual modifiers.

 

Because of run-time binding, we can point to any derived class from the base class object at the run time.

Example :

Class BaseClass{
Public virtual void myfunction()
{
Console.writeline(“This is the base class”);
}
}
class DerivedClass : BaseClass
{
public override void myfunction()  // Overriding virtual method
{
Console.WriteLine("This is the Derived Class");
}
}

we have a virtual method Myfunction() in the BaseClass which is overridden in the DerivedClass

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>