I was playing around with some code today and I wanted to explore a good mixture of polymorphism and inheritance on my example. So, I decided to come up with an example that used interfaces and interface-inheritance. Take a look at the following code:

    // Simple interface defining one method

    public interface ISampleA

    {

        // Leave the definition to the implementor

        void DoTaskA();

    }

 

    // Another simple interface defining one method

    public interface ISampleB

    {

        // Leave the definition to the implementor

        void DoTaskB();

    }

 

    // Make things fun...This interface inherits from the other two

    public interface ISampleC : ISampleA, ISampleB

    {

        // Thus in-turn it supports their

        // method signatures!

    }

 

    // Simple class that implements both 'base' interfaces

    public class Implementor : ISampleA, ISampleB

    {

        // Implementation of ISampleA

        public void DoTaskA()

        {

            Console.WriteLine("Doing task A");

        }

 

        // Implementation of ISampleB

        public void DoTaskB()

        {

            Console.WriteLine("Doing task B");

        }

    }

Pretty straight forward, huh? Two interfaces and one that implements both of them and class that implements two of the three. So how does the CLR interpret this? Well, here's the client that gets to have all the code fun:

    // This is just a test class

    public class Caller

    {

        static void Main(string[] args)

        {

            // This is the poly-inheri fun!

 

            // Create a new instance of the implementor

            Implementor i = new Implementor();

 

            // Can you follow this fun trail?

            ISampleA a = i as ISampleA;

            ISampleB b = a as ISampleB;

            ISampleC c = b as ISampleC;

 

            DoCalls_A(a); // CALL #1

            DoCalls_B(b); // CALL #2

            DoCalls_C(c); // CALL #3

 

            // Wait to exit!

            Console.ReadLine();

        }   

 

        // Only call the methods for ISampleA

        public static void DoCalls_A(ISampleA a)

        {

            a.DoTaskA();

        }

 

        // Only call the methods for ISampleB

        public static void DoCalls_B(ISampleB b)

        {

            b.DoTaskB();

        }

 

        // Since ISampleC implements ISampleA and ISampleB,

        // call their methods respectively

        public static void DoCalls_C(ISampleC c)

        {

            c.DoTaskA();

            c.DoTaskB();

        }

    }

Can you tell me what the output to the console will be at CALL #1, CALL #2 and CALL #3? Have fun!!