Hiding members with Explicit Implementation
suggest changeAn interface can add members the class does not want on its public surface. Explicit implementation keeps those members off the class and available only through the interface.
public interface IMessageService {
void OnMessageReceive();
void SendMessage();
string Result { get; set; }
int Encoding { get; set; }
// yadda yadda
}
Normally you’d implement the class like this.
public class MyObjectWithMessages : IMessageService {
public void OnMessageReceive(){
}
public void SendMessage(){
}
public string Result { get; set; }
public int Encoding { get; set; }
}
Every member is public.
var obj = new MyObjectWithMessages();
// why would i want to call this function?
obj.OnMessageReceive();
The class does not have to offer those members as its own public methods. Declaring them private does not compile: an implicit interface implementation must be public.
Explicit implementation is the way to satisfy the interface without adding the members to the class's public surface:
public class MyObjectWithMessages : IMessageService{
void IMessageService.OnMessageReceive() {
}
void IMessageService.SendMessage() {
}
string IMessageService.Result { get; set; }
int IMessageService.Encoding { get; set; }
}
The members are implemented, and they are not public members of the class. They are not private methods either. A cast to the interface can still call them.
var obj = new MyObjectWithMessages();
/* Compile error: OnMessageReceive is not a member of MyObjectWithMessages.
* It is reachable only through IMessageService. */
obj.OnMessageReceive();
To call an explicitly implemented member, cast the object to the interface:
((IMessageService)obj).OnMessageReceive();