Question

Background: I have a generic collection of type DirectoryCollection<T> and have specified that T must be of type IEntity. I have a concrete type Entity which implements IEntity and two derived types, Employee and Station.

In .NET 4.0 I know that it is possible (from here) to call a method with an IEnumerable<Entity> parameter as DirectoryCollection<Employee>, however, it seems that does not work for a method with a parameter of type ICollection<Entity>. In said method, I use the Remove and Add methods of the collection and consequently, am hesitant to put IEnumerable into the method signature.

What is the best practice in solving this problem?

Was it helpful?

Solution

You need to implement ICollection in the DirectoryCollection class. You may need to implement it explicitly, due to the covariance restriction that @SamHolder mentions in the comments. See this tutorial on implementaing an interface explicitly.

Furthermore, in the methods that accept ICollection<Entity> as a parameter, you may need to change the signature to accept ICollection<IEntity> instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top