Search code examples
c#xmlserializerroslyn-code-analysis

XmlSerializer and array properties C# - Roslyn complains


I had some classes with public array properties which were serialized and deserialized fine. Code Analyzer complained that you should not have arrays as public properties. So I changed (as suggested by CA) my properties to methods, which now set and get my private array fields. Problem: The XmlSerializer does of course not serialize them anymore. What is the best practice to have arrays serialized without the Code Analyzer complaining? I have also tried changing my properties into lists (second suggested solution by CA), but then CA wants them without setter which again lead to no serialization!


Solution

  • Ultimately, you can overrule the CA guidance if your scenario requires it; that's absolutely fine. However! The get-only list should be fine; a typical scenario would be:

    public List<Bar> Bars { get; } = new List<Bar>();
    

    (optionally with some [XmlElement], [XmlArray] or [XmlArrayItem] etc attributes).

    If that doesn't work; please post a minimal example that shows it not working.

    Here's an example of it working:

    class Program
    {
        static void Main()
        {
            var foo = new Foo {
                Bars = {
                        new Bar { X = 42 },
                        new Bar { X = 12 },
                        new Bar { X = 6 },
                    }
            };
    
            var ser = new XmlSerializer(foo.GetType());
            var sw = new StringWriter();
            ser.Serialize(sw, foo);
            var xml = sw.ToString();
            Console.WriteLine(xml);
            var sr = new StringReader(xml);
            var clone = (Foo)ser.Deserialize(sr);
            foreach (var bar in clone.Bars)
                Console.WriteLine(bar.X);
        }
    }
    
    public class Foo
    {
        public List<Bar> Bars { get; } = new List<Bar>();
    }
    public class Bar
    {
        public int X { get; set; }
    }