Why is it that when implementing an interface, if I make the method public I do not have to explicitly specify the interface, but if I make it private I have to…like such (GetQueryString is a method from IBar):
public class Foo : IBar
{
//This doesn't compile
string GetQueryString()
{
///...
}
//But this does:
string IBar.GetQueryString()
{
///...
}
}
So why do you have to specify the interface explicitly when the method is made private, but not when the method is public ?
Explicit interface implementation is a sort of half-way house between public and private: it’s public if you’re using an interface-typed reference to get at it, but that’s the only way of accessing it (even in the same class).
If you’re using implicit interface implementation you need to specify it as public because it is a public method you’re overriding by virtue of it being in the interface. In other words, the valid code is:
Personally I rarely use explicit interface implementation unless it’s required for things like
IEnumerable<T>which has different signatures forGetEnumeratorbased on whether it’s the generic or non-generic interface:Here you have to use explicit interface implementation to avoid trying to overload based on return type.