0

What is this piece of code printing "Hi there" as output? And which of the interface's method is getting executed? Please help me understand it's output..

interface I1
    {
        void display();
    }

    interface I2
    {
        void display();
    }

    class A : I1, I2
    {
        public void display()
        {
            Console.WriteLine("Hi there");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.display();
            Console.ReadLine();
        }
    }
  • What would you expect to happen when executing that? – Nahuel Ianni Apr 01 '17 at 14:22
  • I just want to understand the program flow and execution..I am actually confused.....has display() method been implemented of both the interfaces? – Abhishek Kumar Apr 01 '17 at 14:25
  • 1
    You can look at http://stackoverflow.com/questions/2371178/inheritance-from-multiple-interfaces-with-the-same-method-name It explains what you want to understand. – Girdhar Sojitra Apr 01 '17 at 14:28
  • Possible duplicate of [Inheritance from multiple interfaces with the same method name](http://stackoverflow.com/questions/2371178/inheritance-from-multiple-interfaces-with-the-same-method-name) – Usman Apr 01 '17 at 14:29

1 Answers1

3

Interfaces do not "execute" they represent a contract that ensures that your object will behave in the same way the Interface advertises.

So in this case.. the class A is able to satisfy both interfaces it implements with a single method since both Interfaces require the same method signature. Hence, A is an I1 and an I2 ...

A a = new A();

I1 i1 = (I1)a;
i1.display();

I2 i2 = (I2)a;
i2.display();

Both of these display method invocations still call the one implementation.

Brian Gorman
  • 794
  • 4
  • 8