corert
corert copied to clipboard
XmlSerialization: Deserialization of empty List<string>
trafficstars
Repro:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
[XmlRoot(ElementName = "CounterSet")]
public class CounterSet
{
[XmlAttribute(AttributeName = "name")]
public string EventName { get; set; }
[XmlElement(ElementName = "Counter")]
public List<string> Counters { get; set; }
}
class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(CounterSet));
CounterSet cs = (CounterSet)serializer.Deserialize(new StringReader("<CounterSet name=\"MyCounters\"></CounterSet>"));
if (cs.Counters != null)
{
Console.WriteLine($"PASSED: Counters.Count={cs.Counters.Count}");
}
else
{
Console.WriteLine("FAILED: NULL");
}
}
}
Actual: FAILED: NULL
Expected: PASSED: Counters.Count=0
This is bug in reflection-based XmlSerializer. We won't be able to fix this until we move to dotnet/runtimelab.
The workaround it is to intialize the list in constructor, e.g.:
public class CounterSet
{
public CounterSet()
{
Counters = new List<string>();
}
...
}