3

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?

1
  • The Collection class does not implement the Value property of the ICollection Interface because it is not of the type IObject[].If you want to have explicit implementations for concrete Types you should use a generic implementation for Collection. Commented Jan 17, 2019 at 14:11

1 Answer 1

6

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(); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Ah.. totally forgot about the generics.. thank you so much!
As someone who has started to wrap his mind around using generics a lot more in their code, this answer was beautiful and gave me an actual solid example as to why it was useful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.