ChrisBertrandProgramer

My Blog on computing

C#

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..().

Example:

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: