Alex Rivera | Logout

Can't convert List<KeyValuePair<...,...>> to IEnumerable<object>?

Asked 2011-12-20T13:49:20.260
10

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>;
c#
Edit
Report

2 Answers

20

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.

answered 2011-12-20T13:52:25.757
13

Because it is a struct, and not a class : http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx

answered 2011-12-20T13:51:33.973

Your Answer