views:

172

answers:

1

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 ?

+9  A: 

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:

public class Foo : IBar
{
    // Implicit implementation
    public string GetQueryString() 
    {
        ///...
    }

    // Explicit implementation - no access modifier is allowed
    string IBar.GetQueryString() 
    {
        ///...
    }
}

Personally I rarely use explicit interface implementation unless it's required for things like IEnumerable<T> which has different signatures for GetEnumerator based on whether it's the generic or non-generic interface:

public class Foo : IEnumerable<string>
{
    public IEnumerator<string> GetEnumerator()
    {
        ...
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Call to the generic version
    }
}

Here you have to use explicit interface implementation to avoid trying to overload based on return type.

Jon Skeet
Jon, I made amendments to my code in the post, because I did a mistake earlier on in mapping out exactly my code.
Andreas Grech
Okay, editing. The gist of the answer is the same though.
Jon Skeet
Thanks for the edit, and the answer.
Andreas Grech
great explanation Jon :)
TheVillageIdiot