Thursday, July 12, 2012

C# Polymorphism Example


How often we use Polymorphism in our programs? Polymorphism is the core of any modern object oriented programming language and we use it daily almost without thinking of it. But do we remember the basics of Polymorphism? Recently I realized that I forgot simple stuff when I was on a job interview. Therefore today I want to remind about Polymorphism basics in C#. Hopefully it will help you to pass your next job interview.
Ok, let's write three simple classes and play with Polymorphism a little bit:
class A
{
    public virtual void Print()
    {
        Console.WriteLine("class A");
    }
}

class B : A
{
    public override void Print()
    {
        Console.WriteLine("class B");
    }
}

class C : A
{
    public new void Print()
    {            
        Console.WriteLine("class C");
    }
}
As you can see A is the base class. Classes B and C are inherited from A. Note that the Print method of class B has override keyword and the Print method of class C has new keyword. Here comes the tricky part, let's create instances of these classes and see Polymorphism behavior in action:
static void Main(string[] args)
{
    B b = new B();
    b.Print();      //  class B (override)

    A a = (A)b;
    a.Print();      //  class B (override)


    C c = new C();
    c.Print();      //  class C (new)

    a = (A)c;
    a.Print();      //  class A (new)
}
When we use override keyword, in both cases Print method of class B is called. Same behavior when we use a new keyword and calling for Print method from instance of inherited class. But if derived class is cast to an instance of the base class, then method of the base class is called.

Download the source code of this example.

1 comment:

  1. Polymorphism is called a third pillar of OOPs and its completely true that we use it daily, the thing is that we are just not aware of it. This is simple but good example for any beginners who wants to get started with polymorphism.

    ReplyDelete