Making objects behave across a client-server relationship. Part 3 - Serializing the hell out my object.

How to make sure that my object can be serialized in an orderly fashion?

Making sure that my object kan be serialized is simple, we just add the [Serializable] attribute to it.

[Serializable]
public abstract class Element {
...
}

However, since my object has a reference to its Parent object, serializing it will most likely result in a cyclic, never ending, recursion. Fail.

Enter the DataContract.

[Serializable]
[DataContract(IsReference = true)]
public abstract class Element {
...
}

By applying it to my class, it enables serialization and deserialization with, for instance, the DataContractSerializer. I simply apply the [DataMember] attributes to all members I want to serialize, and voilá, I get a nice and clean, reference enabled, serialization.

But, you might ask, how does this work with the fancy List implementation we did?

Simple, there's a [CollectionDataContract] attribute available for that. That ensures that my List gets serialized to exactly that, and not a stupid array.

Next up: What happens on deserialization.

blog comments powered by Disqus