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

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 interview question: tell a situation where only interface can be used in C# program.

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.

//Interfaces ILoanCustomer & IBankCustomer
//have same method name. That will be implemented
//Explicitely in Customer class
interface ILoanCustomer
{
    void GetCostomerInfo();
}
interface IBankCustomer
{
   void GetCostomerInfo();    
}


class Customer : ILoanCustomer, IBankCustomer
{
    //Explicit implementation of ILoanCustomer interface
    void ILoanCustomer.GetCostomerInfo()
    {
        Console.WriteLine("Loan Customer ...");
        
    }
    //Explicit IBankCustomer of ILoanCustomer interface
    void IBankCustomer.GetCostomerInfo()
    {
        Console.WriteLine("Bank Customer ...");
       
    }
}

//Test
class Program
{
    static void Main(string[] args)
    {
        IBankCustomer bc = new Customer();
        bc.GetCostomerInfo();

        ILoanCustomer lc = new Customer();
        lc.GetCostomerInfo();       
       
    }
}

NOTE:

When a method is explicitly implemented in a class in C#, it cannot be accessed through a class instance if you use class reference, but only through an interface reference pointing to the class instance. For example,

Using interface reference pointing to the Customer class object, class method is accessible.

IBankCustomer bc = new Customer();

bc.GetCostomerInfo();

Using the class reference pointing to the class object, you can’t access the method e.g.

Customer c = new Customer();

c.GetCostomerInfo();

Related Posts