In C#, we cannot inherit multiple classes but we can accomplish multiple inheritance through interfaces. That means we can implement multiple interfaces.
There are some situations where we have requirement to implement multiple interfaces which has method same name and same signature. In this scenario, we cannot find which interface method class implements. To solve this issue, you have to mention interface name before the method name whenever you are implementing the interface method in class.
For example you have two interfaces EmpInterface1, EmpInterface2 which method empName() with the same signature as shown below.
interface EmpInterface1
{
string empName();
}
interface EmpInterface2
{
string empName();
}
Now whenever you are implementing the these two interfaces mention interface name also before the method name as shown below.
class Employee:EmpInterface1,EmpInterface2
{
#region EmpInterface1 Members
string EmpInterface1.empName()
{
return "ABC";
}
#endregion
#region EmpInterface2 Members
string EmpInterface2.empName()
{
return "DEF";
}
#endregion
}
As shown above, we are implementing the EmpInterface1 empName() method as EmpInterface1.empName() and EmpInterface2 empName() method as EmpInterface2.empName().
To access these two methods from client through by creating the object for Employee class and access this object through EmpInterface1 and EmpInterface2 interfaces as shown below.
class Program
{
static void Main(string[] args)
{
EmpInterface1 objEmp1 = new Employee();
EmpInterface2 objEmp2 = new Employee();
Console.WriteLine("EmpInterface1 empName() method result: {0} \nEmpInterface2 empName() method result: {1}", objEmp1.empName(), objEmp2.empName());
Console.ReadLine();
}
}
Here you are accessing the EmpInterface1 empName() method through EmpInterface1 reference and EmpInterface2 empName() method through EmpInterface2 reference.
The output displays as shown below.