Implement two interface with same method in C# – Learn how to implement two interface with same method in C# 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.
If we have two interface with same method name then a class need to implement interface explicitly in a 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();
}
}
Output:
Bank Customer …
Loan Customer …
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();