My blog about computing

Published or updated on the : 2017-05-08

Don’t serialize empty lists with XmlSerializer (C#)

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.


If you find UniversalSerializer useful, please consider supporting the project by donating

Copyright © Christophe Bertrand. All rights reserved.