Wednesday, March 24, 2010

Explicit Interface Implementation

Consider a class, MyClass, that implements an interface, IMyInterface. It is possible to implement the interface member, MyMethod, like this:
string IMyInterface.MyMethod()
{
    // interface implementation
}
In this example, MyMethod is qualified by the interface name, IMyInterface:
IMyInterface.MyMethod()
This is called explicit interface implementation. Assume that we created an object from MyClass using the following statement:
MyClass mc = new MyClass();
We can also create an interface object by casting the class object:
IMyInterface mi = (IMyInterface) mc;
In this case, we can also access MyMethod through the interface object mi. For example:
Console.Write(mi.MyMethod());
Attempting to access MyMethod through the class member mc would generate a compilation error:
Console.Write(mc.MyMethod()); //error
So, when do we need to use this code? There are cases in which the use of explicit interface implementation becomes necessary, such as when the class is implementing two interface and both interfaces contain a method named MyMethod. If the first interface object is mil and the second interface object is mi2, accessing MyMethod through interface objects does not cause any ambiguity. That is:
Console.Write(mi1.MyMethod());
Console.Write(mi2.MyMethod());
In fact, using the class object to access the method will cause ambiguity.
The following example demonstrates a temperature converter that converts from Fahrenheit to Celsius and vice versa. The program contains two interfaces: ITemp1 and ITemp2. Each contains a method named Convert. The class TempConverter explicitly implements the two interfaces. In the Main method, two interface objects, iFC and iCF, are used to access the Convert method.
// Example 8-2
// Explicit interface implementation
using System;
public interface ITemp1
{
    double Convert(double d);
}
public interface ITemp2
{
    double Convert(double d);
}
public class TempConverter: ITemp1, ITemp2
{
    double ITemp1.Convert(double d)
    {
        //Convert to Fahrenheit:
        return ( d * 1.8) + 32;
    }
    double ITemp2.Convert(double d)
    {
        //Convert to Celsius:
        return ( d – 32 ) / 1.8;
    }
}
class MyClass
{
    public static void Main()
    {
        // Create a class instance:
        TempConverter cObj = new TempConverter();
        // Create instances of interfaces
        // Create a From – Celsius – to – Fahrenheit object:
        ITemp1 iCF = (ITemp1) cObj;
        // Create From – Fahrenheit – to – Celsius object:
        ITemp2 iFC = (ITemp2) cObj;
       
        // Initialize variables:
        double F = 32;
         double C = 20;
        // Print results:
        Console.WriteLine(“Temperature {0} C in Fahrenheit: {1:F2}” , C, iCF.Convert( C ));
        Console.WriteLine(“Temperature {0} F in Celsius: { 1:F2}” , F, iFC.Convert(F));
    }
}

No comments:

Post a Comment