Question

Suppose to have an interface like this:

interface MyInterface 
{
    public string AProperty { get; set;}

    public void AMethod ()
}

This interface is used inside another interface:

interface AnotherInterface
{
    public MyInterface member1 { get; set; }

    public int YetAnotherProperty {get; set;}
}

Now suppose to have two classes, one that implements each of the interfaces.

class MyInterfaceImpl : MyInterface
{
    private string aproperty
    public string AProperty
    {
        //... get and set inside
    }

    public void AMethod ()
    {
       //... do something
    }
}

And at last:

class AnotherInterfaceImpl : AnotherInterface
{
    private MyInterfaceImpl _member1;
    public MyIntefaceImpl member1
    {
        //... get and set inside
    }

    ...Other implementation
}

Why does the compiler complain that AnotherInterfaceImpl does not implement MyInterface?

I understand it is a very basic question... but I need to serialize to xml AnotherInterfaceImpl and I cannot do that if member1 is of type MyInterface.

Was it helpful?

Solution

Your class AnotherInterfaceImpl is not actually implementing all members of AnotherInterface. The public property AnotherInterfaceImpl.member1 must have type MyInterface, not MyInterfaceImpl.

Note that this restriction only applies to the public property. The private field AnotherInterfaceImpl._member1 can still be of type MyInterfaceImpl, because MyInterfaceImpl implements MyInterface.

OTHER TIPS

Why the compiler complains that AnotherInterfaceImpl does not implement MyInterface?

Because it doesn't implement it. It has a member that implements it.

That is like saying "my customer object has an orders (list) property; how come my customer isn't a list?"

If you had either:

interface AnotherInterface : MyInterface

or

class AnotherInterfaceImpl : AnotherInterface, MyInterface

then it would be true to say that AnotherInterfaceImpl implemented MyInterface.

you need to "explicitly" type your members as the interface defines them.

class AnotherInterfaceImpl : AnotherInterface
{
    private MyInterfaceImpl _member1;
    public MyInteface member1
    {
        get{ return _member1;}
        set{ _member1 = value;}
    }

    ...Other implementation
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top