The following code is valid since HashSet implements IEnumerable:
IEnumerable<TEdge> edges = new HashSet<TEdge>();
But I get a compile error if I try to use the same as typed values in a Dictionary:
IDictionary<TVertex, IEnumerable<TEdge>> vertexEdges =
new Dictionary<TVertex, HashSet<TEdge>>();
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<TVertex,System.Collections.Generic.HashSet<TEdge>>' to 'System.Collections.Generic.IDictionary<TVertex,System.Collections.Generic.IEnumerable<TEdge>>'. An explicit conversion exists (are you missing a cast?)
What am I missing here? Surely the compiler should be able to figure this out so I'm guessing there either has to be some meaningful decision behind the restriction or I'm doing it wrong.
Because an IDictionary<TVertex, HashSet<TEdge>> is NOT a Dictionary<TVertex, IEnumerable<TEdge>>. If it were, you could add a value that is some other collection of TEdge other than a HashSet.
Similarly, you can't cast a List<Cat> to a List<IAnimal>, otherwise you could add a Dog to the list.
Also note that a cast will fail at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With