Explicit Interface Implementation
In the implementation shown so far, the class that implements the interface (Document
) creates a member method with the same signature and return type as the method detailed in the interface. It is not necessary to explicitly state that Document
is implementing IStorable
, for example; the compiler understands this implicitly.
What happens, however, if the class implements two interfaces, each of which has a method with the same signature? This might happen if the class implements interfaces defined by two different organizations or even two different programmers. The next example creates two interfaces: IStorable
and ITalk
. ITalk
implements a Read( )
method that reads a book aloud. Unfortunately, this conflicts with the Read( )
method in IStorable
.
Because both IStorable
and ITalk
have a Read( )
method, the implementing Document
class must use explicit implementation for at least one of the methods. With explicit implementation, the implementing class (Document
) explicitly identifies the interface for the method:
void ITalk
.Read( )
Marking the Read( )
method as a member of the ITalk
interface resolves the conflict between the identical Read( )
methods. There are some additional aspects you should keep in mind.
First, the explicit implementation method cannot have an access modifier:
void ITalk.Read( )
This method is implicitly public. In fact, a method declared through explicit implementation cannot be declared with the abstract
, virtual
, override
, or ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.