corert icon indicating copy to clipboard operation
corert copied to clipboard

XmlSerialization: Deserialization of empty List<string>

Open jkotas opened this issue 5 years ago • 1 comments
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

jkotas avatar May 01 '20 20:05 jkotas

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

jkotas avatar May 01 '20 20:05 jkotas