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

Authentication using Social Networking portals(Facebook, Gmail, and Yahoo)

There are tons of sites, which offer sign on using the social networking site credentials (Facebook, gtalk, twitter and the list continues).It can be termed a “SINGLE SIGNON” and offers a lot of benefits compared to traditional database authentication approach. However, not storing user credentials in the DB imposes an additional risk. How to track who all logged into the system. Now the question is, which approach to follow. The best approach is to use inbuilt asp.net users for storing the logging info about user activities and using single signon technique for authentication. This article will explore the approach and provide the details of implementation using some third party libraries and customizing it to the requirements. The Authentication will be done using the following networking portals Yahoo  Gmail Facebook    Special thanks to my friend Sumit Khandelwal, for implementation of Facebook part (in fact he did it all!!) Except Facebook, all other ca...

WPF Overview-Part-II

This post is in continuation to the last post. In this Post I’ll be exploring the Dependency Properties Dependency properties are similar to CLR properties with more advanced and complex features. The main difference between the CLR properties and dependency properties is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject . In case this description did not make sense, no need to worry, It will become clear by the time you reach end of this article. How the Value is Resolved in Dependency properties Every time a dependency property is accessed, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not, check if a custom style trigger is active and I the similar manner continues until it finds a value. At last the default value is alwa...

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...