I was trying to build a covariant IEnumerable
for dictionaries via
public interface ICovariantKeyValuePair<K, out V>
{
K Key { get; }
V Value { get; }
}
because I wanted to use only one method to process differently typed dictionaries with some common value type. In the end I was really surprised having overlooked the really simple solution with a generic method
public void Print<S,T>(Dictionary<S,T> dict) { ... }
Now I am wondering what the real benefit of covariant interfaces is and what one is able to do only with these and with no other means.
Edit I understand that it makes sense if I want to keep two values together like it is the case with my covariant Key-Value-Pair described above. The following example from Heinzi (see below)
var kv1 = new CovariantKeyValuePair<string, Dog>("MyDog", myDog);
var kv2 = new CovariantKeyValuePair<string, Cat>("MyCat", myCat);
ICovariantKeyValuePair<string, Animal>[] myAnimals = { kv1, kv2 };
clearly works only with covariant interfaces. But in order to get to the central point let's simplify it further: I can write
Dog d = new Dog();
Cat c = new Cat();
List<Animal> l = new List<Animal>() { d, c };
without the necessity of covariance in my data types.
So the benefit of covariant interface over List<BaseType>
data structures and over methods alike Foo<BaseType>(..)
is for "when needing to keep things together where some inner part has a inheritance relationship attached" like in the case of Key-Value-Pairs?