I’m trying to pass a Dictionary<int, List<T>> into a constructor that requires an IDictionary<int, IEnumerable<T>>.
Unfortunately, the generic IDictionary is not defined as IDictionary<TKey, out TValue>. Perhaps this wouldn’t make sense, but is there a cast that would allow me to pass my dictionary into the constructor?
The obvious cast ((IDictionary<int, IEnumerable<T>>)dictionary) fails at runtime.
No, because that would not be safe:
And you just added an array to a dictionary that can only hold lists. This isn’t allowed because there is no way to make it safe.
You note that the dictionary interface is not covariant; it is precisely this reason why it cannot be covariant. The “out” in the covariant annotation is a mnemonic that is telling you “the value parameter is only used for output”, but clearly the value parameter is used for input into a dictionary.