0

BinaryFormatter.Serialize is deprecated so I am switching to XmlSerializer. The expected behavior is that public members are serialized. If the object being serialized is IEnumerable<T> something different happens. Public members are not serialized and the enumerable is serialized (even if private).

public class Thing : IEnumerable<int>
{
    public bool flag; // ignored !
    internal int ignored; // ignored as you would expect
    private List<int> list; 
    public List<int> publicList; // ignored !
    internal Thing() 
    {
        this.list = new List<int>(); this.list.Add(456); 
        this.publicList = new List<int>(); this.publicList.Add(789); 
    }
    public void Add(int i) { this.list.Add(i); }
    public IEnumerator<int> GetEnumerator()
    {
        return ((IEnumerable<int>)list).GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)list).GetEnumerator();
    }
}

The result in XML Notepad...

image

Notice in the image ArrayOfInt is not even the correct identification. The invocation...

    var thing = new Thing();
    thing.flag = true; thing.ignored = 123;
    Serialize(thing.GetType(), thing, "TestThing.xml");

The helper...

private static void Serialize(Type t, object o, string path)
{
    var s = new XmlSerializer(t);
    using (var sw = new StreamWriter(path))
    {
        s.Serialize(sw, o);
        sw.Close();
    }
}

I have tested a very similar object that lacks the IEnumerable<T> implementation and it appears normal and member identification is normal. I have more than one object that needs to be IEnumerable<T> and I am trying to avoid a rewrite of these objects. Binary serialization seemed painless so this is a surprise. What is the simplest solution to replacing binary serialization?

H2ONaCl
  • 10,644
  • 14
  • 70
  • 114
  • See also https://stackoverflow.com/questions/109318/using-net-what-limitations-if-any-are-there-in-using-the-xmlserializer – Peter Duniho Feb 24 '21 at 08:31
  • The behavior you're asking about is well-documented. See proposed duplicates for in-depth discussion about the special treatment of collection types. – Peter Duniho Feb 24 '21 at 08:32
  • @PeterDuniho from your linked answer, "a property that returns the enumeration" is the simplest alternative implementation for the target classes, possibly making XmlSerializer readily usable. – H2ONaCl Feb 24 '21 at 08:42

0 Answers0