Interface Implementation in C#

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

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.

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

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

Leave a Reply

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