See the following code snippet:
(IEnumerable<object>)new Dictionary<string, string>()
The above cast will throw an invalid cast exception.
Actually, IDictionary<TKey, TValue>
also indirectly implements IEnumerable<out T>
, because it also implements ICollection<T>
. That is, the whole cast should be valid.
In fact, for me it is even more strange that if I run the whole cast on a debugger watch slot, it works!
What's going on?
IEnumerable<T>
which has a covariant type parameter. Even when covariance won't work with value types.............Am I mistaken? – LeonoreleonsisIEnumerable<out T>
– LeonoreleonsisIEnumerable<string>
isn't the same type asIEnumerable<int>
but when you implement these, you're implementingIEnumerable<out T>
– Leonoreleonsisshort s; var o = (object)s; var i = (int)o;
it cannot determine that what is actually ino
is ashort
, and the only way for this to work would be to spin up at runtime a small instance of the compiler to find the appropriate conversion method. My understanding is the debugging features of VS already are using their own instance of the compiler, so there is no benefit in this limitation. – Semela