We
know that a class can implement more than one interface, now what if a class implements 2 interfaces and if both
the interfaces contain a method with the same name and signature, how do we
implement these methods in the class body. This is where explicit Interface
comes into play. In such cases the method name should be prefixed with the
interface name and a (.) symbol.
The following example contains 2 interfaces IEmployee and IDepartment, both the interfaces contain a method GetName() with the same name and signature. The class OfficeClass implements both the interfaces and implements the GetName method from both the interfaces using Explicit Interface Implementation.
The following example contains 2 interfaces IEmployee and IDepartment, both the interfaces contain a method GetName() with the same name and signature. The class OfficeClass implements both the interfaces and implements the GetName method from both the interfaces using Explicit Interface Implementation.
interface IEmployee
{
string GetName();
}
//
interface IDepartment
{
string GetName();
}
//
class OfficeClass
: IEmployee, IDepartment
{
string IEmployee.GetName()
{
return "test
employee";
}
//
string IDepartment.GetName()
{
return "test
department";
}
}
Though
both the interfaces have methods
with the same name and signature, it is mandatory to implement methods from
both the interfaces failing which will lead to a compiler error as follows.
interface IEmployee
interface IEmployee
{
string GetName();
}
//
interface IDepartment
{
string GetName();
}
//
class OfficeClass
: IEmployee, IDepartment
{
string IEmployee.GetName()
{
return "test
employee";
}
}
Error:
OfficeClass does not implement interface member IDepartment.GetName()
No comments:
Post a Comment