views:

44

answers:

3

I just came across this weird behavior today:

interface IFooBar
{
    void Foo();
    void Bar();
}

class FooBar : IFooBar
{
    void IFooBar.Foo()
    {
    }

    void IFooBar.Bar()
    {
        this.Foo();
    }
}

The line this.Foo(); raises the compiler error

'MyProject.FooBar' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'MyProject.FooBar' could be found (are you missing a using directive or an assembly reference?)

If I choose public methods instead of the interface.method declaration style, the code compiles:

class FooBarOk : IFooBar
{
    public void Foo()
    {
    }

    public void Bar()
    {
        this.Foo();
    }
}

I'd like to understand why this error is raised, and how it can be worked around using the interface.method notation

A: 

This is called explicit interface implementation. It lets you implement an interface without exposing those methods publicly. For example you could implement IDisposable but provide a public Close() method which may make more sense to the users of your api. Internally the IDisposable.Dispose() method would call your Close method.

interface IFooBar
{
    void Foo();
    void Bar();
}

class FooBar : IFooBar
{
    void IFooBar.Foo()
    {
    }

    void IFooBar.Bar()
    {
        ((IFooBar)this).Foo();
    }
}

is a way for you to call the Foo method

Kleinux
+1  A: 

Have you tried using the interface syntax in code?

((IFooBar)this).Foo ();

I expect it's because the implementation is effectively hidden, ensuring that you must cast it to an IFooBar in order to use it.

Kieron
+1  A: 

To work around it, you can write:

((IFooBar)this).Foo();

Take a look at the Explicit Interface Implementation Tutorial for answer why this.Foo() doesn't work.

Jim Mischel
Thank you for the link and the magic sentence: "When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface."
devio