.NET Basics: The difference between an explicit and implicit implementation of an interface

The using of interfaces are fundamental in .NET or – in this case – in C#. There are two ways to implement interfaces: The implicit or the explicit way.

The following examples use a base class and two interfaces as seen below:

public class InterfaceImp
{

}

public interface Interface1
{
    void Echo(string message);
}

public interface Interface2
{
    void Echo(string message);
}

The popular and common way is implicit implementation. This means that all defined methods and properties of the interface were implemented without any reference to the interface itself.

public class InterfaceImp : Interface1
{
    public void Echo(string message)
    {
        Console.WriteLine("Echo: " + message);
    }
}

The explicit implementation is the only way if two interfaces were implemented and the defined methods or interfaces have the same name, as seen in the code below.

public class InterfaceImp : Interface1, Interface2
{
    void Interface1.Echo(string message)
    {
        Console.WriteLine("Echo: " + message);
    }

    void Interface2.Echo(string message)
    {
        Console.WriteLine("Echo: " + message);
    }
}

The difference of the two possibilities appears while using of the class. Implicit implementation could be called directly, explicit implementations not.

To solve this behavior it is necessary to cast the class to the wanted interface.

InterfaceImp imp = new InterfaceImp();

((Interface1)imp).Echo("Bla");

((Interface2)imp).Echo("Bla");

As you might expect, explicit implementations cannot be used in derived classes, implicit implementations can.

Advertisements
This entry was posted in C#, Development and tagged , . Bookmark the permalink.

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