Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert Dictionary List<string> type parameter to ICollection<string>

When I try and compile the following code:

Dictionary<string, ICollection<string>> foo = new Dictionary<string, List<string>>();

I get:

CS0029: Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>' to 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.ICollection<string>>'

Why do I get this error when List<string> implements ICollection<string>?

like image 864
Simon Morgan Avatar asked Oct 23 '25 14:10

Simon Morgan


1 Answers

Just think about it for a minute:

Dictionary<string, ICollection<string>> foo 

This is a dictionary of string and ICollection<string>. You could for example add a pair of stringand HashSet<string> as that implements ICollection<string>.

= new Dictionary<string, List<string>>();

Whoa... now you would add that HashSet to a Dictionary of string and List? How would that work? A HashSet is not a List. Well, it won't work. That's why you get errors.


Maybe a better example. Assume both Wolf and Sheep implement IAnimal.

Dictionary<string, IAnimal> animals = new Dictionary<string, Sheep>();

animals.Add("wolf", new Wolf());

What happened to your Dictionary<string, Sheep>? There would be a Wolf in there now! That cannot be. That's why it does not work.

like image 104
nvoigt Avatar answered Oct 25 '25 02:10

nvoigt