Skip to main content

C# Polymorphism


What it is..
Polymorphism literally means existence of more than one form for a single entity.
In context of C# , a  Class can be used as more than one type; it can be used as its own type, any base types, or any  Interface type if it implements interfaces.
Every type in C# is polymorphic.

Polymorphism-Quick Review

A class derived from base class, inherits all the methods, fields, properties and events of the base class. The data and behavior of a base class can be changed using any one of the following two options

1. Use new keyword and replace the base class member in the derived class

For Example:
public class MyBase
{
    public void ReachOffice() { }
    public int Intime;
    public int OutTime
    {
        get { return 0; }
    }
}
 
public class MyDerived : MyBase
{
    public new void ReachOffice () { }
    public new int Intime;
    public new int OutTime
    {
        get { return 0; }
    }
}

Here the use of new keyword  hides the base class member and the new class members are called, when an object for the class is created.

MyDerived mdclass = new MyDerived ();
Mdclass. ReachOffice()

Hidden class members can still be called if an instance of the derived class is cast to an instance of the base class. For example:


MyBase Mbaseclass=( MyBase)mdclass;
Mbaseclass. ReachOffice();


2. Over-ride virtual base class member.

If an instance of a derived class has  to completely take over  from a base class members, the base class has to declare that member as virtual. Derived classes can then  override the base class member, to replace the base class implementation with its own.
For example:
public class MyBase
{
    public virtual void ReachOffice() { }
    public virtual int OutTime
    {
        get { return 0; }
    }
}
 
public class MyDerived : MyBase
{
    public override void ReachOffice () { }
    public override int OutTime
    {
        get { return 0; }
    }
}

When a derived class overrides a virtual member, that member is called even when an instance of that class is being accessed as an instance of the base class. For example:
The new overridden method is called in both the cases.
MyDerived mdclass = new MyDerived ();
Mdclass. ReachOffice()

MyBase Mbaseclass=( MyBase)mdclass;
Mbaseclass. ReachOffice();
As the overridden  virtual member is called regardless of which type(Base/Derived) the caller is using, it show that derived class has changed the initial basic behavior of the base class.(Polymorphism).

Virtual members remain virtual indefinitely. If class PP declares a virtual member, and class QQ derives from PP, and class RR derives from QQ, class RR inherits the virtual member, and has can override it, even if class QQ has  overridden that member. For example:
public class PP
{
    public virtual void MyVirtualMethod() { }
}
public class QQ : PP
{
    public override void MyVirtualMethod () { }
}
public class RR : QQ
{
    public override void MyVirtualMethod () { }
}
A derived class can stop virtual inheritance by declaring an override as sealed. For example:
public class RR : QQ
{
    public sealed override void MyVirtualMethod () { }
}
Now if a  class SS derives from RR,  it cannot override MyVirtualMethod.
Now if the requirement is there to replace MyVirtualMethod, it can be done using new keyword, but not to forget, it will not be overridden.
It will simply hide the base class implementation For Example:
public class SS: RR
{
    public new void MyVirtualMethod () { }
}
In this case, if MyVirtualMethod is called on SS using a variable of type SS, the new MyVirtualMethod is called. If a variable of type RR, QQ, or PP is used to access an instance of SS, a call to MyVirtualMethod will follow the rules of virtual inheritance, routing those calls to the implementation of MyVirtualMethod on class RR.
A derived class that has replaced or overridden a method or property can still access the method or property on the base class using the base keyword. For example:
C#
public class MyBase
{
    public virtual void BaseMethod () { }
}
public class MyDerived: MyBase
{
    public override void BaseMethod () { }
}
C#
public class Derived2: MyDerived
{
    public override void BaseMethod ()
    {
        // Call BaseMethod on Derived to get Derived 's behavior:
        base. BaseMethod ();
    }
}

This tutorial was a quick overview of Polymorphism as implemented in C#.

From now on, I’ll be starting a series of articles where I’ll cover the advanced topics of Threads.
Till then..Happy Coding!!                         


                                                            



























Note:
Fields cannot be virtual; only methods, properties, events and indexers can be virtual.

Comments

Popular posts from this blog

Asp.Net 4.0: An Overview-Part-III

This is the last post in the series which will explore the following new features of ASP.Net 4.0  Performance Monitoring for Individual Applications in a Single Worker Process Web.config File Refactoring Permanently Redirecting a Page Expanding the Range of Allowable URLs Performance Monitoring for Individual Applications in a Single Worker Process It is a common practice to host multiple ASP.NET applications in a single worker process, In order to increase the number of Web sites that can be hosted on a single server. This practice results in difficulties for server administrators to identify an individual application that is experiencing problems. ASP.NET 4 introduces new resource-monitoring functionality introduced by the CLR. To enable this functionality, following XML configuration snippet is added to the aspnet.config configuration file.(This file is located in the directory where the .NET Framework is installed ) <?xml version="1.0" encoding="UTF-8...

WCF-REST Services-Part-II

HOW REST is implemented in WCF Part-I of the series explored the REST conceptually and this post will explore how REST is implemented in WCF. For REST implementation in WCF, 2 new attributes namely WebGetAttribute and WebInvokeAttribute are introduced in WCF along with a URI template mechanism that enables you to declare the URI and verb to which each method is going to respond. The infrastructure comes in the form of a binding ( WebHttpBinding ) and a behavior ( WebHttpBehavior ) that provide the correct networking stack for using REST. Also, there is some hosting infrastructure help from a custom Service¬Host ( WebServiceHost ) and a ServiceHostFactory ( WebServiceHostFactory ). How WCF Routes messages WCF routes network messages to methods on instances of the classes defined as implementations of the service. Default behavior ( Dispatching ) for WCF is to do this routing based on the concept of action. For this dispatching to work, an action needs to be present in ev...

WebMatrix-The Swiss Army knife from Microsoft

  What’s more in store for Web developers, ASP.Net 4.5(with full support for HTML 5 , CSS 3 amd Javascript) and to complement it, is the new awesome tool-WebMatrix. WebMatrix combines five products in one, letting you install, develop, optimize, deploy and manage your sites and databases. With support for the latest web standards like HTML5 & CSS3, multiple frameworks like ASP.NET & PHP, and multiple database engines like MySQL & SQL Server ..and what’s even better…it FREE!! ! ( Download Webmatrix ). To learn more about webmatrix, I recomment the following video. WebMatrix-An intro The tools promises a lot and I have already downloaded a copy and started playing with it. Hope the information  here is useful. Till next we connect…. Happy Learning.