My Blog on computing


Don’t serialize empty lists with XmlSerializer

When you serialize an empty collection/list with XmlSerializer, an element is written.
If you don’t want anything to be serialized, you can use this trick: add a function ShouldSerialize..().


public class Myclass
    public List setters;
    public bool ShouldSerializesetters()
    { return setters != null && setters.Count > 0; }

The function name is “ShouldSerialize”+<the collection field or property name>

The XmlSerializer will detect this function automatically and ask it to know if it should serialize the corresponding field or property, or not.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: