10 February 2013

What is explicit interface implementation

In a previous post mentioned about different types interface implementation and also discussed on implicit interface implementation.

In this post let's discuss about what is explicit interface implementation.

public interface Interface1
 {
   void Method(int parameter);
 }

public interface Interface2
 {
   void Method(int parameter);
 }

Two interfaces, Interface1 & Interface2. Both the interfaces have the same method name or method signature.Let's create a class which implements the two interfaces implicitly and see what happens.

public class ClassExample : Interface1, Interface2
{
 public void Method(int parameter)
   {
     Console.WriteLine("Am I implementation of 
              Interface1 or Interface2?"
);
   }
}

As you can see looking at the class which implements the two interfaces, it's not possible to tell whether Method() is of Interface1 implementation or it is of Interface2 implementation. We cannot distinguish them, as it is just one implementation. But if you have design requirement where a class has to provide different implementation of Method(), then implementing the interface implicitly will not work.

To address this problem, the implementing class has to name the interface method implementations explicitly. Let's see what does this mean.

public class ClassExample : Interface1, Interface2
 {
  public void Interface1.Method(int parameter)
  {
    Console.WriteLine("I'm the implementation of 
                     Interface1"
);
  }
  public void Interface2.Method(int parameter)
  {
    Console.WriteLine("I'm the implementation of 
                     Interface2"
);
  }
}

So the Methods names are prefixed with the interface names. Interface names are explicitly specified along with the interface implementation and hence the name explicit implementation.

Let's see an example.

public class Program
{
  static void Main(string[] args)
  {
    ClassExample instance = new ClassExample();
    // Cannot access Method() by using 
    // the ClassExample type variable.

    Interface1 interface1 = instance;

    // Interface1.Method() can be accessed by using 
    // the variable declared of Interface1 type
    interface1.Method(1);

    Interface2 interface2 = instance;

    // Interface2.Method() can be accessed by using 
    // the variable declared of Interface2 type
    interface2.Method(1);    
  }
}

That means, when a class implements interfaces explicitly, the variables declared of class type cannot access any of the interface methods. However, when class instances are typecasted to interface variables, the respective interface methods can be accessed.

No comments:

Post a Comment