How to extend an explicitly implemented interface

Let's say you were creating a control that derives from a built in webcontrol. You might want to add some new fun stuff to the current control's implementation of IPostBackDataHandler. Unfortunately, all the built in controls implement IPostBackDataHandler privately, using c#'s explicit interface implementation feature. What this means to you is that there is no built-into-the-language way to override that implementation at all. If you implement the interface, only your implementation can ever be called. So if you want to extend an explicitly implemented interface, you actually have to reimplement everything that the base class does in its implementation. Ack.

As you can imagine, I was not happy with that. So, I came up with a hack way around this problem that serves my needs.

public interface IFoo {
  void Bar();
}
public class ClassA : IFoo {
  void IFoo.Bar() {
    Console.WriteLine("IFoo.Bar from ClassA");
  }
}
public class ClassB : ClassA, IFoo {
  void IFoo.Bar() {
    base_IFoo_Bar();
    Console.WriteLine("IFoo.Bar from ClassB");
  }
  private void base_IFoo_Bar() {
    //Here's the fun stuff!
    System.Reflection.InterfaceMapping interfaceMap = typeof(ClassA).GetInterfaceMap(typeof(IFoo));
    for ( Int32 i=0; i< interfaceMap.InterfaceMethods.Length; i++ ) {
      if ( interfaceMap.InterfaceMethods[i].Name == "Bar" ) {
        interfaceMap.TargetMethods[i].Invoke(this,null);
        break;
      }
    }
  }
}

15 Comments

Comments have been disabled for this content.