Dean Dean - 3 months ago 14
ASP.NET (C#) Question

KeyValuePair from WCF - conversion error when consuming via ASP.Net

I have a WCF web service which is returning a KeyValuePair. ie:

List<KeyVauePair<string,int>>


When I test this in the WCF Test Client it says the type returned is:

System.Collections.Generic.KeyValuePair<System.Collections.Generic.KeyValuePair<System.String,System.Int32>>


So thats good and dandy. I then go to consume this web method in ASP.Net via:

List<KeyValuePair<string, int>> testkv = WCF.GetOptionSetValues("contact", "types");


But this does not work and the compiler says:

Cannot implicitly convert type System.Collections.Generic.KeyValuePair[] to System.Collections.Generic.List System.Collections.Generic.KeyValuePair

For some reason it seems the compiler thinks the return type from the web method is:

System.Collections.Generic.KeyValuePair[]


But its not an array. Its a:

System.Collections.Generic.KeyValuePair


I am wondering why the compiler is interpreting the web method as KeyValuePair[] instead of KeyValuePair?

Answer

A Collection of KeyValuePair and a List of KeyValuePair are not the same thing. If you want a List, you probably need to iterate through your collection and build one.

foreach (KeyValuePair<string, int> pair in WCF.GetOptionSetValues("contact", "types"))
{
    myList.Add(pair);
}