Why doesn't this work in C#?
var dict1 = new Dictionary<int, System.Collections.IEnumerable>();
dict1[0] = new List<string>(); // OK, because implements IEnumerable
var dict2 = new Dictionary<int, List<string>>();
dict1 = (Dictionary<int, System.Collections.IEnumerable>)dict2; // Compiler error CS0030
We can clearly see that every value in dict2
must implement IEnumerable
because it is a List<T>
, so why can't I assign it to a Dictionary<int, System.Collections.IEnumerable>
? Is there a way to do this?
My use case here is that I have some code that wants to use the more specific stuff in (in this example) the List<string>
, but some other code that needs to take an IEnumerable
dictionary. I can explicitly cast in every predicate to get access to the more specific stuff, but it seems pretty messy and I'd rather have a reference to the (same) Dictionary where its value's type is actually List<string>
:
var dict1 = new Dictionary<int, System.Collections.IEnumerable>();
dict1[0] = new List<string>(); // OK, because implements IEnumerable
var result = dict1.Where(x => ((List<string>)x.Value).Capacity > 100);