Friday 20 February 2009

To serialize, or not to serialize - that is the question

When serializing objects, you sometimes want to exclude properties that don't meet a certain criteria. This validation could be a simple check for default/null values or a more complicated scenario.

This example shows how to prevent a DateTime property being serialized if it hasn't been set, meaning it's value will be DateTime.MinValue. You'll notice there is the property for date of birth and a method called ShouldSerializeDateOfBirth that has no parameters and returns a boolean value. If this returns true, serialize, and vice versa. How does it get called I hear you ask. I don't actually know exactly but the key to invoking is in the name - make sure it starts with "ShouldSerialize" followed by the name of the property (in this case, "DateOfBirth").

public bool ShouldSerializeDateOfBirth() { return DateOfBirth != DateTime.MinValue; }

[XmlElement("dateofbirth")]
public DateTime DateOfBirth { get; set; }

No comments: