I've been trying to serialize a class (see below) which inherits from List<int>
and has fields that provide extra information.
Originally, I had been using XmlSerializer
, however I was having issues there as well.
According to this post it is by design with XmlSerializer
does not serialize fields but DataContractSerializer
should work.
Any suggestions would be greatly appreciated!
[CollectionDataContract]
public class Group : List<int>
{
[DataMember]
public string Key { get; set; }
}
static void Main()
{
Group test = new Group { Key = "Test key" };
test.Add(60);
DataContractSerializer serializer = new DataContractSerializer(typeof(Group));
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, test);
stream.Position = 0;
test = serializer.ReadObject(stream) as Group;
Console.WriteLine("{0}: {1}", test.Key ?? "No luck", test[0]);
}
Thanks, Noah
This is the expected behavior. When deriving from a collection only base class will be serialized :) I would suggest creating a base wrapper class.
[DataContract]
class SuperWrapper {
private List<int> _myList;
private string _name;
[DataMember]
public List<int> Items { get { return _items; } set { _items = value; } }
[DataMember]
public string Name { get { return _name; } set { _name = value; } }
}