If I try and do:
IDictionary<uint, IEnumerable<string>> dict = new Dictionary<uint, List<string>>();
I get the error:
error CS0266: Cannot implicitly convert type 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'. An explicit conversion exists (are you missing a cast?)
If I add the cast:
IDictionary<uint, IEnumerable<string>> dict = (IDictionary<uint, IEnumerable<string>>)new Dictionary<uint, List<string>>();
Then it compiles.
Why do I need the explicit cast? And is it safe? I thought the whole point on covariance was the ability to implicitly cast safely?
EDIT: C# prevents unrelated casting eg
string s = (string)0L;
error CS0030: Cannot convert type 'long' to 'string'
It does allow explicit downcasting of related types when you know that the object is actually a subclass:
Animal animal = new Cat();
Cat cat = (Cat)animal;
I am confused why the compiler is offering, and allowing me to explicitly cast to an IDictionary with incompatible types.