HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE


QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Polymorphism in C#
Polymorphism and inheritance are related. To better understand polymorphism, you must understand inheritance concepts first. If you havent read inheritance article, please read inheritance in C# article before proceeding. 
 
Example to understand Polymorphism

using System;

public class Customer

{

    public virtual void CustomerType()

    {

        Console.WriteLine("I am a customer");

    }

}

public class CorporateCustomer : Customer

{

    public override void CustomerType()

    {

        Console.WriteLine("I am a corporate customer");

    }

}

public class PersonalCustomer : Customer

{

    public override void CustomerType()

    {

        Console.WriteLine("I am a personal customer");

    }

}

public class MainClass

{

    public static void Main()

    {

        Customer[] C = new Customer[3];

        C[0] = new CorporateCustomer();

        C[1] = new PersonalCustomer();

        C[2] = new Customer();

 

        foreach (Customer CustomerObject in C)

        {

            CustomerObject.CustomerType();

        }

    }

}

We know that classes are reference types. In the below example we have a customer class. In the main method we create an instance of the Customer class.
                Customer C = new Customer();
 
Here C is a reference variable and not an object by itself. C will be pointing to customer object in the memory. For a clear understanding of Classes and reference variables please read classes in C# article.

As C is a reference variable of type Customer class, it can only point to an object of type Customer and it cannot point to any other object type unless the Customer class is related to some other class thru inheritance.

If we have another class CorporateCustomer and if both Customer and CorporateCustomer classes are related by inheritance as shown in the example below, then Customer class reference variable can be pointed to an object of type CorporateCustomer class.

In our example Customer class is the base class for CorporateCustomer class. As we know from inheritance concepts a base class reference variable can point to a child object type. Based on this, Customer class reference variable can be used to point to CorporateCustomer object.
              Customer[] C = new Customer[3];
              C[0] = new CorporateCustomer();

We have yet another class, PersonalCustomer which is also deriving from Customer class. For CorporateCustomer class and PersonalCustomer class the base class is the same Customer class. As these classes are related by inheritance the following statements are perfectly legal.
              C[0] = new CorporateCustomer();
              C[1] = new PersonalCustomer();

If you have noticed all the 3 classes have the same method CustomerType(). This method is marked as virtual method in the Customer class. When we mark a method as virtual in the base class, it means that the derived class which inherits this method can override the method and provide its own implementaion as shown in our example. The derived class can use the inheritted virtual method without overriding.

In our example both the CorporateCustomer class and PersonalCustomer class override the inheritted CustomerType() method and provides their own implementation.

In the Main() method we have created Cutomer array, which can hold 3 objects of type Customer. For discussion on arrays please read arrays in C# article.
            Customer[] C = new Customer[3];

In the code snippet below, we are assigning a new CorporateCustomer object and new PersonalCustomer object to a reference variable of type Customer. This is possible as the classes are related by inheritance and we know a parent class reference variable can point to a child class object.
           C[0] = new CorporateCustomer(); 
           C[1] = new PersonalCustomer();
           C[2] = new Customer();

Finally in the Main() method we loop thru the CustomerObject array using foreach loop and invoke the CustomerType() method. For discussion on loops please read loops in C#.

The ouput of the above program is shown below.
          I am a corporate customer
          I am a personal  customer 
          I am a customer


We know that in the Customer array
         FirstObject is CorporateCustomer class object.
        SecondObject is PersonalCustomer class object.
        ThirdtObject is Customer class object.

The output shows that the overriden methods from the respective classes are invoked during the run time. This is called as polymorphism.
Definition of Ploymorphism from MSDN:
Through inheritance, 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. This is called polymorphism.

In other words, the base class object reference variable can do different things(example invoke different methods) depending on the child class object the reference variable is pointing to.
Key points to remember about Ploymorphism
The derived classes may or may not override the inherted virtual methods. In our example if the the derived class PersonalCustomer doesnot override the CustomerType() method then the base class virtual method will be invoked. To test this just comment the CustomerType() method in PersonalCustomer class and run the program.
.NET Framework examples
We know that every type in .NET is derived from object class directly or indirectly. The object class has 4 methods as listed below.
  1. Equals()
  2. GetHashCode()
  3. GetType()
  4. ToString()
Even the classes that we write will derive from the object class. So all the methods in the object class are inherited to our class as well. So the Customer class below will also have the 4 methods. I am invking the ToString() instance method which is inherited from the object class. For a clear understanding of static and instance methods please read methods in C#.

The output before overriding the ToString() method is:
         Customer 

This is not useful information at all. When I invoke C.ToString(), I would like to see the customer FirstName and LastName. To achieve this we will have to override the ToString() method in our class. In the object class in .NET framework the ToString() is a virtual method. So you can either use the ToString() method as is, or provide your own implementation by overriding it as shown in the example below.

The output after overriding the ToString() method is:
        Prasad Cherukuri

using System;

public class Customer

{

    string FirstName;

    string LastName;

   

    public Customer()

    {

        FirstName = "Prasad";

        LastName = "Cherukuri";

    }

 

    //Comment and uncomment this overriden method to see

    //how the out put changes

    public override string ToString()

    {

        return FirstName + " " + LastName;

    }

}

 

public class MainClass

{

    public static void Main()

    {

        Customer C = new Customer();

        Console.WriteLine(C.ToString());

    }

}


Njoy Programming
   ByPrasad Cherukuri


What is polymorphism in C# with examples and code samples. Inhertance, Virtual and Overriden methods 9/29/2008 1:29:13 PM - By indu

Give me a simple example for

can polymorphism be possible with interfaces if yes give me one example.



Sample Program - Achieve polymorphism with interfaces 10/1/2008 10:41:49 AM - By Prasad Cherukuri

Yes polymorphism is posiible with interfaces. A sample program that shows how to achieve polymorphism with interfaces is listed below.

In this example, Customer is an interface. CorporateCustomer and PersonalCustomer classes inherit from Customer interface and both these classes provide implementation for the CustomerType() method declared in the interface.

In the Main method the respective overriden CustomerType() method is called.

using System;
interface Customer
{
    void CustomerType();
}

public class CorporateCustomer : Customer
{
    public void CustomerType()
    {
        Console.WriteLine("I am a corporate customer");
    }
}

public class PersonalCustomer : Customer
{
    public void CustomerType()
    {
        Console.WriteLine("I am a personal customer");
    }
}

public class MainClass
{
    public static void Main()
    {
        Customer[] C = new Customer[2];
        C[0] = new CorporateCustomer();
        C[1] = new PersonalCustomer();

        foreach (Customer CustomerObject in C)
        {
            CustomerObject.CustomerType();
        }
    }
}



What is meant by remoting and What are all the steps involved to implement a Remoting in Real Time E 10/20/2008 12:12:32 AM - By Sivakumar
What is meant by remoting and What are all the steps involved to implement a Remoting in Real Time Envinoment


Your Questions/Comments/Feedback:
If you have some questions that needs an answer you can post them here. If you find this page useful please post your comments and feedback.
Title/Question:
Name:
Email:
Comments: