Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Folks,
Today I was going through concepts of Interfaces in C# and came across an example on Interface. Please see the following:

Interface code:
C#
using System;
using System.Collections.Generic;
using System.Text;
namespace ClassLibrary1
{
    public interface IAClass
    {
        int AddNumber(int a, int b);
    }
    public interface IBClass
    {
        int AddNumber(int a, int b);
    }
    public class Class1: IAClass, IBClass
    {
        public int AddNumber(int a, int b)
        {
            return a + b;
        }
    }
}


Console Application Code:
C#
using System;
using System.Collections.Generic;
using System.Text;
using ClassLibrary1;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IBClass obj = new Class1();

            Console.WriteLine(obj.AddNumber(3, 6));
        }
    }
}


I am getting the output as 9, which is correct. Now my question is that I have declared same method in both interfaces, with same signature. Class1 is implementing both Interfaces. If I am creating the object of IAClass or IBClass output is same, how does the compiler understand that which method it should call?
Why is it not throwing any error?
Posted

Your interface is simply a contract it states that any class that implements it must satisfy the criteria as stated in the interface.

In your example both interfaces specify the same method requirement and as your class satisfies this requirement both interfaces are equally happy.

There is no error as the compiler does not care how the method is implemented as long as the requirement is met.
 
Share this answer
 
v2
Comments
BillW33 1-Aug-12 9:13am    
Another good answer, +5
Your implementing class will have one method and this will satisfy the requirements of both interfaces. It doesn't matter what type of reference variable it calls, the same method will always be executed.

Check this.

http://stackoverflow.com/questions/4638218/class-implementing-two-interfaces-which-define-the-same-method[^]
 
Share this answer
 
Comments
Vani Kulkarni 1-Aug-12 6:16am    
Thanks Santosh, understood now!
Santhosh Kumar Jayaraman 1-Aug-12 6:18am    
Welcome.
BillW33 1-Aug-12 9:13am    
Good answer, +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900