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"

Covariance and Contravariance-General Discussion

If you have just started the exploration of .Net Framework 4.0, two terms namely Covariance and Contravariance might have been heard. The concept that these terms encapsulate are used by most developer almost daily, however there has never been any botheration about the terminologies. Now, what actually these terms mean and how are these going to affect us as a developer, if we dive in to the details. The simple answer is it’s always good to know your tools before actually using them. Enough philosophy, let’s get to the business. Starting the discussion let me reiterate that in addition to Covariance and Contravariance, there is another terminology, Invariance. I’ll by start here by diving into the details of Invariance and then proceed further. Invariance: Invariance can be better understood by considering the types in .Net.>net has basically two type, value-types and reference-types. Value types (int, double etc) are invariant i.e. the types can’t be interchanged either

Advanced WCF

In this post, I am sharing the link of articles about  advanced topics in WCF. The List of articles is exhaustive and can serve as your repository for all WCF queries. Concurrency,Throttling & Callbacks  WCF Concurrency (Single, Multiple and Re entrant) and Throttling   WCF-Interop and BinarySecurityToken  WCF Callbacks  Creating Web Services From WSDL Link1 Link2 Link3 Link4 WCF-Security WCF over HTTPS   Transport Security(basic)/HTTPS UserNamePasswordValidator ServerCertificateValidationCallback 9 simple steps to enable X.509 certificates on WCF - CodeProject http://www.codeproject.com/KB/WCF/9StepsWCF.aspx?display=Print Message Security(Certificate)/PeerTrust Securing WCF Services with Certificates. - CodeProject http://www.codeproject.com/KB/WCF/wcf_certificates.aspx Message Security(Certificate)/ChainTrust How To Configure WCF Security Using Only X.509 Certificates - CodeProject http://www.codeproject.com/KB/webservices/WCFx509S