Implicit/Explicit Implementation of Interface in C#

In C#, we have two ways to implement interfaces:

  1. Implicit Implementation
  2. Explicit Implementation

To see the difference, Let’s say we have an interface:

public interface IDemoInterface
{
string Name { get; set; }
void DemoMethod();
}

As we implement this interface, we will notice that Visual Studio or Visual C# Express gives us an option like

If we select Implement Interface ‘IDemoInterface’ (which is implicit one) we will see the generated code like:

class Class1 : IDemoInterface
{

#region IDemoInterface Members

public string Name
{
get
{ //some implementation }
set
{ //some implementation }
}

public void DemoMethod()
{
//method implementation
}

#endregion
}

whereas in contrast if we have selected Explicitly implement interface then we would have seen an implementation like

class Class2 : IDemoInterface
{
#region IDemoInterface Members

string IDemoInterface.Name
{
get { //some implementation }
set { //some implementation }
}

void IDemoInterface.DemoMethod()
{
//method implementation
}

#endregion
}

So you must have noticed that in explicit implementation, the interface name is explicitly mentioned with the property and the method but of course that is not the only difference 🙂

Then what does it mean? and what is the real difference?

Well explicit implementation allows the interface members to be accessible only when the object is cast to interface type 🙂 Means that when I will instantiate an object of Class 1, I will be able to access interface members in contrast to Class 2 in which I have to cast the object to that particular interface. Not clear, consider the code below:

In contrast, when you create object of Class 2 you will not be able to see Interface members

until or unless you cast that object into interface type…

image

When interface members are explicitly implemented, they are not accessible through class instance instead through interface instance.

Beside this another noticeable point is that when implemented explicitly the members’ name become InterfaceName.MemberName and hence multiple interfaces with same member name can implement in the class whereas this is not possible in the implicit implementation. A disadvantage of Explicit implementation is that when used with value types, Boxing can cost performance.