Skip to content

Interface implementation

George George

Asked May 3, 2008, 4:20 AM EDT3 answers
Share
LinkedInX

Hello everyone,


I am migrating from C++ to C#. The following compile error makes me confused. Suppose in interface there is a method called Abc which returns object, and in the implementation class, there is also a method called Abc, but the return type is List<int>, I think List<int> is already a type (derived type) of object, so no need to explicitly implement Interface.Abc again, but here is a compile error.

[Code]
D:\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs(14,11): error CS0738: 'MyList.Foo' does not implement interface member 'MyList.IFoo.Abc()'. 'MyList.Foo.Abc()' cannot implement 'MyList.IFoo.Abc()' because it does not have the matching return type of 'object'.
[/Code]

Could anyone show me what is the rule I break here please?

[Code]
public class MyList
{

    interface IFoo
    {
        object Abc();
    }

    class Foo : IFoo
    {
        public Foo()
        {

        }
       
        public List<int> Abc()
        {
            return new List<int>;
        }

    }

    static void Main()
    {
        Foo f = new Foo();
        return;
    }
}
[/Code]


thanks in advance,
George

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    public class MyList
    {
        interface IFoo
        {
            object Abc();
        }

        class Foo : IFoo
        {
            public Foo()
            {

            }

            public object Abc()   //Must return type of object
            {
                return new List<int>();
            }
        }

        static void Main()
        {
            Foo f = new Foo();
            List<int> myList = (List<int>)f.Abc(); //Cast it back

            return;
        }
    }

    0
  • 0
    The formatting was all messed up there, but the interface was implementing a member that returned type "object" and you were implementing that member in MyList, however you had the wrong return type on it, it needed to return type "object" :)
    0
  • 0

    Thanks Brandon,

     

    Your reply is clear.

     

    regards,

    George

    0