Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to cast IDictionary<T, HashSet<S>> to IDictionary<T, IEnumerable<S>>?

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.

like image 714
tugend Avatar asked Oct 26 '25 04:10

tugend


1 Answers

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.

like image 101
D Stanley Avatar answered Oct 27 '25 18:10

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!