Wednesday, August 29, 2007

Explicit Interface Implementation

Suppose that theClass is derived from two different and unrelated interfaces: Interface1 and Interface2. Further suppose that each of these interfaces has a method: theMethod() with the same signature. The question is how to define theClass so that each theMethod() is implemented. To do this requires what is called an explicit implementation. An explicit implementation requires that at least one of the implemented methods of theClass has its name preceded with the name of the interface (which in this case is called an explicit implementation of the method). When this is done, the implemented method does not have an access specifier. An explicit implementation helps to distinguish which implementation is being used if there is more than one.

For example the two methods could be defined in the class as in the following:



theMethod()
{
....
}
Interface2.theMethod()
{
....
}




That is suppose the program contained the following code:



interface Interface1
{
void theFirstOne();
void theMethod();
}
interface Interface2
{
void theSecondOne();
void theMethod();
}
class theClass: Interface1, Interface2
{
. ........
public void theFirstOne()
{
.....
}
public void theSecondOne()
{
......
}

// The following will implement the Interface1 method
//
public void theMethod()
{
...
}
// The following will be an explicit implementation of
// the Interface2 method. Notice no access specifier.
//
Interface2.theMethod()
{
....
}
}




so that when defining an instance of theClass, as in the following:



theClass theObject = new theClass();




and then the call of theMethod() would be the following:



theObject.theMethod();




but this would be calling theMethod() that was derived from the interface: Interface1 without any additional explicit notation.

In order to access the explicit implementation: Interface2.theMethod() a reference to the interface: Interface2 must be declared as in the following:



Interface2 theReference = (Interface2) theObject;




Then, using theReference, the explicit implementation may be accessed as in the following:



theReference.theMethod();




For an example of this concept see: explicitImplimentation.cs

The example above only made one of theMethod() functions an explicit implementation. What may be desirable would be to make each an explicit implementation. Some authors on C# recommend that each method inherited from an interface be an explicit implementation. In this way there would be fewer problems when the code was modified by other programmers or if the code was in the component library with little or no documentation to warn about the problems that may be encountered deriving a class from the component interfaces.

No comments: