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>?
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.
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