Getting an InvalidCastException when trying something like this :
IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>();
However, this did work:
IEnumerable<object> test = (IEnumerable<object>)new List<Dictionary<string, int>>();
So what's the big difference? Why can a KeyValuePair not be converted to an object?
Update: I should probably point out that this did work:
object test = (object)KeyValuePair<string,string>;
First of all Dictionary is already a collection of KeyValuePairs, therefore the second example is casting the entire Dictionary to an object, not the KeyValuePairs.
Anyway, if you want to use the List, you need to use the Cast method to convert the KeyValuePair structure into an object:
IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<object>();
That's because KeyValuePair<K,V>
is not a class, is a struct. To convert the list to IEnumerable<object>
would mean that you have to take each key-value pair and box it:
IEnumerable<object> test = new List<KeyValuePair<string, int>>().Select(k => (object)k).ToList();
As you have to convert each item in the list, you can't do this by simply casting the list itself.
Because it is a struct, and not a class : http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx
A KeyValuePair
is a struct and doesn't inherit from class object.
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