Explicit vs Implicit Interface member implementations
July 4, 2010 Leave a Comment
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?
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.