1

I need a collection that has an Add method and a covariant type parameter.

IEnumerable of T covers the covariant type parameter

public interface IEnumerable<out T> : IEnumerable

but it has no Add method.

IList of T does not have a covariant type parameter but has the Add method.

Does anyone know a collection that would cover this or how to make one?

millimoose
  • 39,073
  • 9
  • 82
  • 134
user2005657
  • 607
  • 10
  • 20

2 Answers2

3

IEnumerable<out T> means that "values of this type can be assigned to a variable of any type IEnumerable<X> where X is T or a parent of T"

If you had something like IList<out T>, that would mean you could do the following:

IList<string> strings = new List<string>();
IList<object> objects = strings; 
objects.Add(new object());

Obviously this is not type-safe, which is why no such interface can exist.

millimoose
  • 39,073
  • 9
  • 82
  • 134
0

One cannot have an interface which is a covariant with respect to T and includes an an Add method that takes type T, since one that would imply that a collection which was capable of accepting any type of Dog was capable of accepting any type of Animal. One could define a Contravariant interface IFeedable<in T> with an Feed method which took a parameter of type T (I prefer "feed" to "add", since the latter term can also refer to an arithmetic operation, and since the existence of an object which can accept objects and do something with them does not imply that those objects are being added to some sort of a collection; for example, one could easily have a filtering class which took an IFeedable<T> and a Predicate<T> and implemented IFeedable<T> by taking every T it was given, called the predicate function, and passed the item to the supplied IFeedable<T> only if the predicate returned true. Data given to such a method wouldn't necessarily be "added" to any sort of collection, but would nonetheless be "fed" to the object implementing the interface.

supercat
  • 77,689
  • 9
  • 166
  • 211