Click to See Complete Forum and Search --> : interface implementation


George2
May 3rd, 2008, 08:18 AM
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.


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


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


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;
}
}



thanks in advance,
George

hspc
May 3rd, 2008, 08:55 AM
Method must have the same signature, this will work:
public object Abc()
{
return new List<int>();
}
But your code won't.

George2
May 3rd, 2008, 09:00 AM
Thanks hspc,


I think must be the same type for both return type and input parameter type, derived type does not work, right?

Method must have the same signature, this will work:
public object Abc()
{
return new List<int>();
}
But your code won't.


regards,
George

hspc
May 3rd, 2008, 09:21 AM
I think must be the same type for both return type and input parameter type, derived type does not work, right?
Yes,From msdn:
To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member

George2
May 3rd, 2008, 09:23 AM
Good to learn from you, hspc! I will mark it as resolved.

Yes,From msdn:


regards,
George

Arjay
May 3rd, 2008, 12:51 PM
Now, that's what I'm talking about. :thumb: