Interface Implementation in C#

I recently found a piece of code that can be summarized by the following sample:

interface I
{
   void F1();
   void F2();
}

class X 
{
   public void F2() { Console.WriteLine("F2"); }
}

class A : X, I
{
   public void F1() { Console.WriteLine("F1"); }
}

As you can see there is an interface I that has two methods, F1 and F2. A is derived from X, that has a method F2, and also implements I, but only contains F1. I was puzzled at first, because I was expecting that A was explictitly implementing all the methods defined in the interface I. But F2 was implemented in X, its base class. After thinking a little bit it all become clear. This was a normal behavior of the compiler.

When a class A implements an interface I it guarantees that it supports (implements) the entire contract that the interface defines. But it does not assert that it will explicitly implement all the interface members within its explicit definition. I’m stressing on the explicit word here, because A extends (is derived from) X. That means A is an X. Everything that X exposes (i.e. what is visible to its derived classes) is part of A too.

In our case, F2, implemented in X, is also available to A, because A is an X. Since both F1 and F2 are members of A, then it means A fully implements I, which makes the code compile just fine.

How is this helpful? Suppose you have several interfaces that all define one ore several members with the same meaning.

interface I1
{
  void F1();
  void F2();
  int ErrorCode { get; }
}

interface I2
{
  void G1();
  void G2();
  int ErrorCode { get; }
}

interface I3
{
  void H1();
  int ErrorCode { get; }
}

Instead of providing the same implementation several times, like in the following code, you can have only one implementation for the common functionality.

class A : I1
{
  private int m_errorCode;

  public void F1() {}
  public void F2() {}
  public int ErrorCode { get {return m_errorCode;} }
}

class B : I2
{
  private int m_errorCode;

  public void G1() {}
  public void G2() {}
  public int ErrorCode { get {return m_errorCode;} }
}

class C : I3
{
  private int m_errorCode;

  public void H1() {}
  public int ErrorCode { get {return m_errorCode;} }
}

We can create one class that provides the implementation for ErrorCode and let the others extend it and implement the corresponding interface.

class X
{
  protected int m_errorCode;

  public int ErrorCode { get {return m_errorCode;} }
}

class A : X, I1
{
  public void F1() {}
  public void F2() {}
}

class B : X, I2
{
  public void G1() {}
  public void G2() {}
}

class C : X, I3
{
  public void H1() {}
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.