Saturday, November 04, 2006

Explicit Interface Implementation

I was looking through my study notes when I came across several short programs I wrote sometimes ago that highlight important features of the C# language.  I’ll be posting the same in the coming posts with examples of when to use them.

//Explicit interface definition
//Be able to call an interface method ONLY through that interface

using System;

public class TestInterface : ITestInterface
{
     public void Method1()
     {
          Console.WriteLine("Method 1 Called");
     }     

     public void CallMethod1()
     {
          Method1();
     }
     public void CallMethod2()
     {
          ((ITestInterface)this).Method2();
          Method2();
     }


     ///ITestInterface implementation
     ///Two separate implementations of methods, both explicit and implicit
     

     //Explicit interface implementation
     void ITestInterface.Method2()
     {
          Console.WriteLine("Method 2 Called through ITestInterface");
     }

     //Implicit interface implementation
     public void Method2()
     {
          Console.WriteLine("Method 2 called through the class reference");
     }
}

public class InterfaceCaller
{
     public static void Main()
     {
          TestInterface ti = new TestInterface();
          ti.CallMethod1();
          ti.CallMethod2();
          ti.Method2(); //No such method compiler error if implicit interface implementation is omitted.
     }
}




public interface ITestInterface
{
     void Method1();
     void Method2();
}


Usage Scenarios:

  • Explicit Interface Implementation: Restrict the method access to be through the defined interface only.

  • While writing wrappers you want to restrict your team members to work only with the interface that you provide.  You may have earmarked the class for refactoring later.

  • Both EII & III: Provide two different implementations of the same method.

  • For me personally, this is dangerous.  Unless your specific situation demands that you employ this feature, it is better to leave this alone.

No comments: