This is a mirror of official site:

C#/.NET Little Wonders: Explicit Interface Implementation

| Monday, February 11, 2013
Most of the time in C#, we implement interfaces implicitly. This is by far the simplest method and makes the method available both to consumers of the interface and the implementing type directly.

There are times, though, when you may want to implement an interface, but hide or change how the interface implementation is exposed in the implementing type.  This is done through explicit interface implementation, which we will discuss today. 

Implicit Interface Implementation

Implementing interfaces in C# is easy, we simply have our implementing type satisfy the interface by having it contain a member which satisfies the interface (or can be abstract of course).  The easiest way to do this is with implicit implementation.

So, for example, say we have a sample interface (yes, I could make it a generic, but bear with me for now):

   1: public interface IFactory
   2: {
   3:     object Create();
   4: }

We can implicitly implement this interface by creating a type that has a method with the same signature and return type:

   1: public class SentenceBuilder : IFactory
   2: {
   3:     // ...
   5:     // Because this method has the same signature and return type, it
   6:     // is considered an implicit interface implementation
   7:     public object Create()
   8:     {
   9:         return “Both class and interface see this.”;
  10:     }
  11: }

When we do this, we call the same method whether we call the method from an instance of IFactory or SentenceBuilder:

   1: // same object, one as SentenceBuilder, one as Factory 
   2: var builder = new SentenceBuilder(); 
   4: IFactory factory = builder; 
   6: // result will be the same regardless of the reference we call from 
   7: Console.WriteLine(factory.Create()); 
   8: Console.WriteLine(builder.Create()); 

Many times, this is sufficient for our needs. But sometimes, we’d like a little bit more control of how a type implements an interface while still being required to satisfy the interface contract. This is where explicit interface implementation comes into play.

Read more: James Michael Hare
QR: Inline image 1

Posted via email from Jasper-net