Tom van der Woerdt
Tom van der Woerdt

Reputation: 29985

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

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>;

Upvotes: 10

Views: 4831

Answers (4)

Strillo
Strillo

Reputation: 2982

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>();

Upvotes: 3

Fischermaen
Fischermaen

Reputation: 12468

A KeyValuePair is a struct and doesn't inherit from class object.

Upvotes: 3

Guffa
Guffa

Reputation: 700800

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.

Upvotes: 20

mathieu
mathieu

Reputation: 31192

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

Upvotes: 13

Related Questions