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...
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?