5

I'm trying to implement a very simple interface and use it to access a property of a type that is itself accessed through an interface like so:

interface ITest
{
    IOther Other { get; }
}

interface IOther { }

class Other : IOther { }

class Test : ITest
{
    public Other Other { get; set; }
}

However I get the following build error:

Error   13  'Test' does not implement interface member 'ITest.Other'.   'Charger.Shared.Test.Other' cannot implement 'ITest.Other' because it does not have the matching return type of 'IOther'.

Now I understand what the error is saying, but I can't understand why. 'Other' implements 'IOther' so why the problem?

An imperfect solution would be to explicitly implement the interface:

class Test : ITest
{
    public Other Other { get; set; }

    IOther ITest.Other
    {
        get { return this.Other; }
    }
}

Why is this boilerplate necessary?

Thanks.

EDIT: Assume that in the actual non-example code where I'm having this problem, declaring Test as this is not an option:

class Test : ITest
{
    public IOther Other { get; set; }
}
mistakenot
  • 554
  • 3
  • 14
  • Imagine that I want to set to the `Other` property an instance of `Another` class that is also implementing `IOther` interface... – Vova Oct 04 '15 at 23:25
  • Extra code is required to convert Other to IOther. You don't write that code, but it still exists, the C# compiler generates it automatically. Have a look see with ildasm.exe. Where does this code live? It can't be inside the property getter, it must return Other. It can't live inside the caller, it doesn't know any better than it gets an IOther and has no way to know that it actually gets Other. There's nowhere to put it, an unsolvable problem. You must therefore *say* it returns IOther, now there's a place to put it. In the getter. – Hans Passant Oct 04 '15 at 23:29
  • IOther might be implemented by other classes also. When you are declaring the foot print of ITest you are saying that ITest has an object reference of type of interface IOther. This resolution is done at compile time by c#. and hence compiler expects exactly same type. – D J Oct 04 '15 at 23:32
  • @Vova the interface doesn't specify the setter. So it's not a problem. – Sign Oct 04 '15 at 23:55
  • Right but this is a particular case. However, in general this will be an issue, right? – Vova Oct 04 '15 at 23:56

0 Answers0