How to implement two interface with same method in C#?

(Last Updated On: February 26, 2019)

Answer includes two interface with same method in C# implementation and how to call them with a c# code example. Here is the exact interview question asked : If you implement two interface with same method name in a program then doesn’t method call conflict? In another word, how to call same method from two interfaces in c#? Show them by C# code example.

Answer: If we have two interface with same method name then a class need to implement interface explicitly in a program.

[Note: For this interview question, an interviewer expects explanation of explicit interface implementation with a complete program example. Merely saying that we can implement interface explicitly if two interfaces have same method name is not sufficient. Recommended to read another interesting question i.e.  a situation where only interface can be used in C#]

 

We implement the interface explicitly in a class, using interface name e.g. “interfacename.method()”

void ILoanCustomer.GetCostomerInfo()

Also note that when we use explicit interface implementations, the functions are not public in the class.

In below C# program example, we have two interfaces ILoanCustomer and IBankCustomer. Both have same method name i.e. GetCostomerInfo();

Customer class will implement both interfaces explicitly.

 

NOTE:

When a method is explicitly implemented in a class in C#, it cannot be accessed through a class instance, but only through an interface instance. For example

Using interface instance, class method is accessible.

IBankCustomer bc = new Customer();

bc.GetCostomerInfo();

 

Using class instance can’t access the method e.g.

Customer c = new Customer();

c.GetCostomerInfo();