What is the difference between covariance and contra-variance in programming languages? [closed]

Covariance is pretty simple and best thought of from the perspective of some collection class List. We can parameterize the List class with some type parameter T. That is, our list contains elements of type T for some T. List would be covariant if S is a subtype of T iff List[S] is a subtype … Read more

Why is Function[-A1,…,+B] not about allowing any supertypes as parameters?

Covariance and contravariance are qualities of the class not qualities of the parameters. (They are qualities that depend on the parameters, but they make statements about the class.) So, Function1[-A,+B] means that a function that takes superclasses of A can be viewed as a subclass of the original function. Let’s see this in practice: class … Read more

Can I Override with derived types?

You can re-declare (new), but you can’t re-declare and override at the same time (with the same name). One option is to use a protected method to hide the detail – this allows both polymorphism and hiding at the same time: public class Father { public Father SomePropertyName { get { return SomePropertyImpl(); } } … Read more

Getting a vector into a function that expects a vector

vector<Base*> and vector<Derived*> are unrelated types, so you can’t do this. This is explained in the C++ FAQ here. You need to change your variable from a vector<Derived*> to a vector<Base*> and insert Derived objects into it. Also, to avoid copying the vector unnecessarily, you should pass it by const-reference, not by value: void BaseFoo( … Read more

How to get around lack of covariance with IReadOnlyDictionary?

You could write your own read-only wrapper for the dictionary, e.g.: public class ReadOnlyDictionaryWrapper<TKey, TValue, TReadOnlyValue> : IReadOnlyDictionary<TKey, TReadOnlyValue> where TValue : TReadOnlyValue { private IDictionary<TKey, TValue> _dictionary; public ReadOnlyDictionaryWrapper(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(“dictionary”); _dictionary = dictionary; } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public IEnumerable<TKey> Keys … Read more

Question about C# covariance

Simply put, IList<T> is not covariant, whereas IEnumerable<T> is. Here’s why… Suppose IList<T> was covariant. The code below is clearly not type-safe… but where would you want the error to be? IList<Apple> apples = new List<Apple>(); IList<Fruit> fruitBasket = apples; fruitBasket.Add(new Banana()); // Aargh! Added a Banana to a bunch of Apples! Apple apple = … Read more