Question

I'm using the WCF DataContractSerializer to serialize and deserialize a large object graph in my application. My problem is that if I have a collection that is initialized on the field declaration, the DataContractSerializer does not run that initialization, and the collection ends up null.

For example:

class Test
{
    List<string> collection = new List<string>();

    public List<string> Collection 
    {
         get { return collection; } 
    }
}

After serializing and deserializing this class, the collection will be null instead of the default new. If I move the initialization into the property get, it works ok.

Since I have a pretty large object graph, going through all the places that this happens is rather time consuming. I'd prefer if there was a way to do this automatically somehow.

Update: I'm using the WCF DataContractSerializer, so I guess that's why it doesn't initialize the collection.

Can the regular XML Serializer handle recursive references as I've got those in my entity?

Update: Ok, so now I'm stuck... to be more specific, the entities are used for NHibernate, so they do have DataContract/DataMember on them. But then I'm using IList for the BelongsTo/HasMany properties, and XMLSerializer doesn't serialize those either, and with the no recursive references, that's a no go either.

So, assuming we have a class that uses IList, and has recursive references, is there a way I can serialize/deserialize it and still run the default object constructors ?

Update: did some more tests, looks like I'm going to have to come up with a hybrid of my own, as NH requires the IList, which restricts me to DCS, and its tag along problems...

Was it helpful?

Solution

XmlSerializer runs the constructor / field-initialisers; the code as-written should be fine. Are you perhaps usig DataContractSerializer (i.e. WCF) instead? (DCS doesn't run constructors).

A handy hack for WCF is:

get {
    return list ?? ( list = new List<string>() );
}

OTHER TIPS

The easiest way to resolve this is to initialize the collection in the default constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top