mistakenot
mistakenot

Reputation: 614

Why do I need an explicit interface declaration here? (C#)

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

Upvotes: 5

Views: 61

Answers (0)

Related Questions