bene_rawr
bene_rawr

Reputation: 119

How to use an interface in an interface

I want to create an interface which can handle multiple other object of one interface.

I tried using the interface in the interface and using an object in the new class.

public interface IObject
{
    double Value { get; set; }
}

public class FirstObject: IObject
{
    double Value { get; set; }
}

public class SecondObject: IObject
{
    string Titel { get; set; }
    double Value { get; set; }
}

public interface ICollection
{
    IObject[] Values { get; set; }
}

public class Collection: ICollection
{
    SecondObject[] Values { get; set; }
}

Now I get the error, that my Collection doesn't implement the IObject[] Values member.

I thought when I use an object (SecondObject) which is implementing from the interface IObject the Collection should handle this.

What am I doing wrong and how can I solve this?

Upvotes: 3

Views: 111

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

You might be off better here using generics:

public interface ICollection<T> where T : IObject
{
    T[] Values { get; set; }
}

public class Collection : ICollection<SecondObject>
{
    public SecondObject[] Values { get; set; }
}

The reason that it doesn't work now, is that the signature should match exactly. That means the Values should be an array of IObject, which it isn't. Using generics you can solve this, while keeping the type constraint.

A second, but inadvisable solution would be using an explicit interface implementation:

public SecondObject[] Values { get; set; }

IObject[] ICollection.Values
{
    get
    {
        return this.Values;
    }
    set
    {
        this.Values = value?.Cast<SecondObject>().ToArray();
    }
}

Upvotes: 6

Related Questions