Interface 101: Explicit Interface Implementation using C#

The primary motivation of introducing inerface is to enforce OO-style of thinking while revoking the drawbacks of multiple inheritance. In fact, the support for explicit interface implementation is an important tool in OO-developers’ toolbox. Utilizing this concept, we can implement multiple interfaces in a class, and still no ambiguity gets introduced.

In fact, explicit interface implementation ensures private accessibility via interface reference. That is, in order to access any member of a class that implements an interface explicitly, an interface reference is required, which supports the concept called “Run-time Bindings“, and introduces a higher level of abstraction.

In the rest of the post we focus on following–

glyphicons Defining interfaces,
glyphicons Implementation of the interfaces explicitly,
glyphicons Advantages of explicit interface implementation.

To do so, we start by defining interfaces and shows how to apply explicit interface implementation using an example. Please note that, this is a simple and contrived example, intended only to be illustrative.

The following class Calculator implements both interfaces using explicit interface implementation.

Now that we have implemented these interfaces, next we see outlines several examples to show how to use this implementation. The first example below tries to use the Add method without interface reference.

Therefore, it gets a compile time error as the implementation is private and can only be accessed via interface reference as follows.

As we have notice that the both interfaces have Add as a member. In fact, Calculator class also implements both Add method via polymorphic references. Next example shows how to invoke ICalculator.Add by using an instance of Calculator.

To sum up, the key take-aways from this discussion regarding explicit interface implementation are as follows.

glyphicons It make the whole implementation Abstract/Private . That is , you need the interface reference to access that implementation.

glyphicons It allow you to implement multiple Interface and at the same time, does not introduce any ambiguity. So, the polymorphic reference or runtime binding can be implement very efficiently.

We highly appreciate any comment or query regarding this post. Thanks!

See More


Revisions

[R-1: 02-04-2013] Updated formatting to make this post more consistent with current CSS.

Advertisements

3 thoughts on “Interface 101: Explicit Interface Implementation using C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s