DataContractSerializer not serializing properties of custom collections

66 Views Asked by At

I've found similar questions from people about properties of objects within a collection, but my question is about a property of the collection itself. In the example below, the Something property of the Collection doesn't make the trip back from serialization.

How can I make DataContractSerializer serialize the Something property of the collection? I am aware of the workaround of making a property outside the collection object, but this negates the reason for even using custom collections (the ability to add properties to it in the future).

This happens with NetDataContractSerializer and XmlSerializer as well.

Objects

[DataContract]
public class TempClass
{
    [DataMember]
    public TempStuffCollection Collection { get; set; }
}

[CollectionDataContract]
public class TempStuffCollection : List<TempStuff>
{
    [DataMember]
    public string Something { get; set; }
}

[DataContract]
public class TempStuff
{
    [DataMember]
    public string Foo { get; set; } = "Bar";
}

Serialization Helpers

public TempClass Deserialize(byte[] serializedBytes)
{
    using (Stream memoryStream = new MemoryStream(serializedBytes))
    {
        DataContractSerializer deserializer = new DataContractSerializer(typeof(TempClass));
        TempClass storeMessage = (TempClass)deserializer.ReadObject(memoryStream);
        return storeMessage;
    }
}

public byte[] Serialize(TempClass storeMessage)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(TempClass));
        serializer.WriteObject(memoryStream, storeMessage);

        return memoryStream.ToArray();
    }
}

Example Program

void Main()
{
    var o = new TempClass
    {
        Collection = new TempStuffCollection
        {
            new TempStuff(),
            new TempStuff(),
            new TempStuff(),
        }
    };

    o.Collection.Something = "this should still be here";

    var serialized = Serialize(o);
    var deserialized = Deserialize(serialized);

    // Outputs: 3
    Console.WriteLine(deserialized.Collection.Count);
    // Outputs: null
    Console.WriteLine(deserialized.Collection.Something ?? "null");
}

Output

3
null
0

There are 0 best solutions below