WCF Serialization Part 2c: Hacking the NameValueCollection (unsuccesfully)

As we mentioned here and here, I've been struggling to get the NameValueCollection object to pass through WCF serialization. Please read the first two posts first for some context.


In the previous episodes, we saw that we can't get WCF to serialize the NameValueCollection (NVC, from now on) because it incorrectly marked for its CollectionDataContract serialization, but then choked because it had no Add(object) method.


So to take the most direct approach, I subclassed the NameValueCollection and added my own Add(object) implementation to see if this jedi mind trick will let WCF work with the NVC class:


public class NVC : NameValueCollection


    public void Add(object obj)





Once I did this, the WCF stopped yelling at me that the contract was invalid, but (naturally) my data would vanish during transfer.


So next I tried putting a breakpoint inside my Add() method to see what object is passed to it – I was hoping for something along the lines of a KeyValuePair or even a DictionaryEntry, something I can use to manually recreate my NVC.

Turns out there's no such luck – even though the NVC has an internal object called NameObjectEntry that the NVC uses internally for storage, it's not exposed externally. Even the GetEnumerator() method returns an enumerator that only goes over the Keys, not a key/value dictionary.

This means that when recreating my dictionary, the value passed to my Add() method is a single string with the key name only, and the value is lost in translation.


No luck there, either.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.