Possible Duplicate:
In C#, why can't a List<string> object be stored in a List<object> variable
Why doesn’t the below work?
List<string> castMe = new List<string>();
IEnumerable<string> getFromCast = (IEnumerable<string>)castMe; // allowed.
Dictionary<int, List<string>> castMeDict = new Dictionary<int, List<string>>();
Dictionary<int, IEnumerable<string>> getFromDict = (Dictionary<int, IEnumerable<string>>)castMeDict; // Not allowed
Is this a flaw in the Dictionary casting mechanism, or in my thinking that this should be allowed?
Thanks.
In your thinking. You are expecting that dictionaries should be covariant in their conversions. They are not, for the following reason. Suppose they were, and deduce what could go wrong:
An array of string is convertible to
IEnumerable<string>but not toList<string>. You just put something that is not a list of string into a dictionary that can only take list of string.In C# generic types may be covariant or contravariant if all the following conditions are met:
Most of those conditions are not met for dictionary — it is not an interface or delegate, it is not provably safe, and the type is not marked as safe for variance. So, no variance for dictionaries.
IEnumerable<T>by contrast does meet all those conditions. You can convertIEnumerable<string>toIEnumerable<object>in C# 4.If the subject of variance interests you, consider reading my two dozen articles on the subject:
http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/