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

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2012-09-21T03:20:49Z Indexed on 2012/09/21 3:37 UTC
Read the original article Hit count: 122

Filed under:
|
|
|

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'"

© Stack Overflow or respective owner

Related posts about c#

Related posts about compiler