3

Assuming I have this sample class:

public class MyClass
{
    public List<int> ListTest { get; set; }
    public string StringTest { get; set; }
    public int IntTest { get; set; }
}

And this code:

string xmlStr = "<MyClass><StringTest>String</StringTest></MyClass>";
XElement xml = XElement.Parse(xmlStr);
XmlSerializer ser = new XmlSerializer(typeof(MyClass));
using (XmlReader reader = xml.CreateReader())
{
    var res = ser.Deserialize(reader);
}

After the Deserialize is completed the value of res is:
ListTest -> Empty List with Count = 0 (NOT null).
StringTest -> "String" as expected
IntTest -> 0 as expect (default value of an integer).

I'd like the serializer to act the same (default(List<T>) which is null) with List's and not instantiate them.

How can I accomplish something like that?
BTW, I must use the XmlSerializer.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99

1 Answers1

7

You can use backup-property to serialize/deserialize property as array:

public class MyClass
{
    [XmlIgnore]
    public List<int> ListTest { get; set; }
    [XmlElement("ListTest")]
    public int[] _listTest
    {
        get { return ListTest?.ToArray(); }
        set { ListTest = value == null ? null : new List<int>(value); }
    }
    ...
}

Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • Making `ListTest` private and using it as backing field would be better. – Uğur Aldanmaz Jul 08 '18 at 20:20
  • @UğurAldanmaz, there [are problems](https://stackoverflow.com/q/4314982/1997232) to serialize `private` members with `XmlSerializer`. As for a backfield of `List` type suggestion, exposing `T[]` property (with `list.ToArray()` in the getter?) is expensive, I wouldn't do it in general. The idea here is to only tune serialization, leaving `public List` property without changes, because I have no clues about its usage scenarios (maybe it's big, maybe property is called often, maybe it's set often, etc.) – Sinatr Jul 09 '18 at 07:53
  • I've suggested to make it private because it will not be serialized already since it has `[XmlIgnore]` attribute. – Uğur Aldanmaz Jul 09 '18 at 16:21