다음을 통해 공유


C#: Using 2 Interfaces with Same Method Signature in 1 Class

Let's give you a brief description about a common scenario. Let’s say you have two interfaces Interface1, Interface2, and both interfaces are having a method addNumber() with the same signature. Now let’s say you have to implement both interfaces in one class (e.g. Class1: Interface1, Interface2). The question is how will the implementation happen when you implement the method addNumber in class1. How does the run time come to know which Interface method is invoked?

Or let’s say you want to provide different implementations of the same method defined in two different interfaces, what will happen?

Now that the scenario is pretty much clear, it is called Interface Name Conflict or Interface Collisions. Let’s see how we can handle this problem.

You can download the sample code which demonstrates the solution of this problem "Interface Name Conflict" from this link: Sample - C# Interface Collision

Below is the sample code which demonstrates the problem:

Interface Definition:

interface Interface1 
 {
 int addNumber(int x, int y);
 } 
 interface Interface2 
 {
 int addNumber(int x, int y);
 } 
Class that implements both interfaces:
public class  Class1 : Interface1, Interface2 
{
public int  addNumber(int  x, int  y)
 {
 return x + y;
 }
}

As you can see in the above class, the method addNumber is implemented in Class1 and the method belongs to both interfaces. The problem comes into the picture when you have to provide a different implementation of the same method in the same class.

Below sample code demonstrates how you can provide explicit implementation of both interfaces:

public class  Class1 : Interface1, Interface2
{
 int Interface1.addNumber(int x, int y)
 {
 return x + y;
 }
 int Interface2.addNumber(int x, int y)
 {
 return x + y+2;
 }
 }

To call both methods implemented in Class1, you have to type cast the Class1 object into either Interface1 or Interface2, then the respective method call will happen. Below sample code demonstrates the same:

static void  Main(string[] args)
 {
 Class1 obj = new  Class1();
 int x = ((Interface1)obj).addNumber(1, 1);
 int y = ((Interface2)obj).addNumber(1, 1);
 Console.Write("Value of X: {0} and Value of Y: {1} ",  x, y);
 Console.Read();
 }