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

Answers


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();

I don't believe you are instantiating your class. This code should work for you:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IFoo foo = new Foo();
            Console.WriteLine("Will return 10: {0}", foo.Bar());

            foo[10] = 20;
            Console.WriteLine("Will return 20: {0}", foo[10]);
        }
    }

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

    class Foo : IFoo
    {
        private int[] array = new int[100];
        public int Bar()
        {
            return 10;
        }

        public int this[int i]
        {
            get
            {
                if (i >= 100)
                {
                    throw new IndexOutOfRangeException("Maximum range is 100");
                }
                return array[i];
            }
            set
            {
                array[i] = value;
            }
        }
    }
}

Lastly, reducing casts is not the only reason for using interfaces. Interfaces also work well when you are using the Factory Pattern and just general abstraction, which is best described in the Contract Pattern. In other words, you can have multiple classes that inherit from IFoo and you can pass them around to other sections of your code that utilize the contract without actually knowing the class that actually implements the contract (interface).


Need Your Help

excel vba check if command button and checkbox exists

excel vba excel-vba exists commandbutton

I have a script that uses checkboxes and command buttons, and there is a macro that resets them to default on every sheet.

Python Parse XML using xml.dom.minidom - Extract Items within List

python xml dom xml-parsing parsexml

I have lengthy xml this actually ebay listings using ebay api, I am trying to extract following structure in that xml dom:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.