Explicit vs Implicit Interface member implementations

While implementing an interface member in a derived class, there are two variations – Explicit member implementation and Implicit member implementation.

Explicit member implementation
An explicit member implementation includes the interface name as prefix to the method implementation. When an interface member is implemented explicitly it is accessible only by casting to the implemented interface.

Implicit member implementation
An interface member when implemented without the interface name prefix in the deriving class is an implicit implementation.

For example:
interface IListable
{
// Returns the value of each column in the row
string[] ColumnValues
{
get;
}
}

interface IComparable
{
// Compares the object parameter and results with an integer value
int CompareTo(object obj);
}

public class Contact : IListable, IComparable
{

#region IListable Members

// An explicit interface member implementation
string[] IListable.ColumnValues
{
get { throw new NotImplementedException(); }
}

#endregion

#region IComparable Members

// An implicit interface member implementation
public int CompareTo(object obj)
{
throw new NotImplementedException();
}

#endregion
}

public class User
{
public void Method()
{
string[] values;
object obj = 1;
int result;
Contact contact1, contact2;
contact1 = new Contact();
contact2 = new Contact();

// Error: Unable to call ColumnValues() directly
// on a contact.
// values = contact1.ColumnValues;

// For calling an explicit member,
// first cast to IListable
values = ((IListable)contact1).ColumnValues;

// Whereas, an implicit member can be called
// directly from the derived class object
result = contact2.CompareTo(obj);
}
}

When to use which?

  • If the member is not a core part of the class’s functionality and rather a peripheral which would be accessed only by limited, specific classes, the method should be implemented explicitly. It avoids unnecessary listing of the member method as well as provides an additional layer of encapsulation.
  • If there is already a class member with same name it could be beneficial to make an explicit implementation in order to differentiate
  • One more significant point about explicit implementation is that in multi-level inheritance, the method implementation if explicit should be prefixed with the interface name where the method is declared, i.e. a derived interface would not work and will show a compile-time error.

    Advertisement

    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 )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.