Web Design that taps into the haromny and vision of your dreams.

Polymorphism in C#

Baaa! I'm a sheep!

Written By on in C#

506 words, estimated reading time 3 minutes.

Another useful technique in object orientated programming is Polymorphism, which allows you to implement derived class methods through a base class pointer at run time.

Advanced C# Programming Series
  1. C# Advanced Data Types
  2. Using C# Properties and Indexers
  3. C# Event Handling and Delegates
  4. Method Overloading and Overriding in C#
  5. C# Class Abstraction and Encapsulation
  6. C# Aggregation and Advanced Scope Techniques
  7. Polymorphism in C#
  8. Boxing and Unboxing Value Types in C#
  9. C# Operator Overloading
  10. Creating Multi-Threading Applications with C#
  11. Unsafe Code Execution in Microsoft .Net

This is useful for when you need to invoke the methods of objects stored in an array if the objects are not always of the same type. They must be related through inheritance, however, and they have to be added as an inherited type.

class testClass
{
  public virtual void testMethod()
  {
    Console.WriteLine("I am a testClass");
  }
}

We can create a series of derived test classes which inherit from testClass and which also override the testMethod to give their own implementation.

class test1 : testClass
{
  public override void testMethod()
  {
    Console.WriteLine("I am test 1");
  }
}
 
class test2: testClass
{
  public override void testMethod()
  {
    Console.WriteLine("I am test 2");
  }
}
 
class test3 : testClass
{
  public override void testMethod()
  {
    Console.WriteLine("I am test 3");
  }
}

Now we can create an array of test objects and iterate through them using a foreach loop. Full code listing is shown for a console application.

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication2
{
    class testClass
    {
        public virtual void testMethod()
        {
            Console.WriteLine("I am a testClass");
        }
    }
 
    class test1 : testClass
    {
        public override void testMethod()
        {
            Console.WriteLine("I am test 1");
        }
    }
 
    class test2 : testClass
    {
        public override void testMethod()
        {
            Console.WriteLine("I am test 2");
        }
    }
 
    class test3 : testClass
    {
    }
 
 
    class Program
    {
        static void Main()
        {
            testClass[] testArray = new testClass[4];
 
            testArray[0] = new test1();
            testArray[1] = new test2();
            testArray[2] = new test3();
            testArray[3] = new test2();
 
            foreach (testClass test in testArray)
            {
                test.testMethod();
            }
        }
    }
}
 

When running the program the overridden testMethod of each object is called, and for the test3 since it does not override testMethod, the testMethod from the base class is called.

I am test 1
I am test 2
I am a testClass
I am test 2
Press any key to continue . . .

If your base class for the array were test2 instead of testClass, you would not be able to add test1 or test3 to the array. This technique only works if your objects are, or inherit from, the base class of the array. Why? Because test2 could have its own method defined which is not defined within test1 or test2, but a method defined in testClass is guaranteed to be inherited in test2.

It must also be noted that you can only access the methods and properties of the base class, thus if a derived class has its own method or property, it cannot be accessed (as shown in the example below). The AnotherTest method only exists for test class "test3", thus calling it on test2 and test1 will fail. The base class does not contain an entry for AnotherTest thus the compiler will error. There is, however, a way better method which is called Boxing and Unboxing which we will look at in a later tutorial.

class test3 : testClass
{
  public void AnotherTest()
  {
    Console.WriteLine("This is AnotherTest");
  }
}
 
class Program
{
  static void Main()
  {
    testClass[] testArray = new testClass[4];
 
    testArray[0] = new test1();
    testArray[1] = new test2();
    testArray[2] = new test3();
    testArray[3] = new test2();
 
    foreach (testClass test in testArray)
    {
      test.AnotherTest(); // Compiler Error
    }
  }
}
 

Last updated on: Friday 23rd June 2017

 

Comments
Mini

Mini

i dont understand this.

testClass[] testArray = new testClass[4];

Reply to Mini
Tim Trott

Tim Trott

This is an array declaration, creating an array of testClass objects called testArray of length 4.

Hope that helps clear things up.

Reply to Tim Trott
Ali

Ali

Very Good

Reply to Ali

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me