Search code examples
c#syntaxcompiler-errors

C# Why does calling an interface member from a class generate an error?


So I have an interface:

interface IFoo
{
    int Bar();
    int this[int i] {get; set;}
}

And a class that derives from it

class Foo : IFoo
{
    public int IFoo.Bar()
    {
        //Implementation
    {
    public int IFoo.this[int i]
    {
        //Implementation
    }
}

Now, I try to do this:

var fooey = new Foo();
int i = fooey.Bar();

or this:

int i = fooey[4];

I would expect these to work properly. However, the compiler generates an error as if such members don't exist. Why is that? I am aware I can cast Foo as IFoo, but I am also aware that casting is costly to performance, which is often the reason to use interfaces in the first place.

EDIT 1: These are the errors generated

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

"Cannot apply indexing to an expression of type 'Foo'"


Solution

  • You've explicitly implemented IFoo, which means that its members can only be accessed through a reference that's explicitly typed to IFoo:

    // This will work
    Foo fooey = new Foo();
    int i = ((IFoo)fooey).Bar();
    

    If you want the members to be visible without casting, then in your implementations just use the member name by itself, without prefixing it with the interface's name:

    class Foo : IFoo
    {
        public int Bar() { /* implementation */ }
        public int this[int i] { /* implementation */ }
    }
    
    // now this will also work:
    Foo fooey = new Foo();
    int i = fooey.Bar();