I have two interfaces with same method
interface FirstInterface
{
int add(int x, int y);
}
interface SecondInterface
{
int add(int x, int y);
}
class TestInterface:FirstInterface,SecondInterface
{
public TestInterface() {}
public int add(int x, int y)
{
return x + y;
}
}
and in my main class
static void Main(string[] args)
{
TestInterface t = new TestInterface();
int result = t.add(3, 4);
}
The compiler doesnt give any error and the result is displayed..
Is it right ?? shouldn't we use FirstInterface.add
??
does it mean interfaces are resolved at compile time ??
It's the subject of Explicit or Implicit implementation of interfaces.
If you implement Interface A
and Interface B
, and they both have a member called Foo
, which is a method, then if you implement these interfaces in one class, your only method Foo
would count for both of them. This is by design, and frankly, I think there is no other way around for this.
To implement them separately, you have to use Explicit Interface Implementation
, that is, you prefix the name of the Foo
method with the name of the interface and a dot, like InterfaceA.Foo
and InterfaceB.Foo
.
Quoting from C# specification :
20.3 Fully qualified interface member names
An interface member is sometimes referred to by a qualified interface member name. A qualified interface member name consists of a name identifying the interface in which the member is declared, followed by a dot, followed by the name of the member.
This is implicit interface implementation, so the method is now associated with the instance of TestResult as well. This means you can call the method on both instances with the concrete class handle as well as instances with an IFirstInterface handle.
FirstInterface interfaceHandle = new TestInterface();
interfaceHandle.add();
Will also work
What you are doing here is implementing the interface implicitly.with implicit interface implementation you access the interface methods and properties as if they were part of the class itself.
Whereas in explicit implementation you can access them by treating them as interface
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.