Search code examples
c#datacontractserializer

How do I deserialize a List<T> as another List<T> instead of a readonly T[]?


We have some code that makes a copy of a List<T> of objects. The problem is the code is returning a readonly array of T[] instead of a List<T>.

Why is that, and how can I fix this deserialization code?

public interface ITestObject { }

[KnownType(typeof(ITestObject))]
[DataContract(Name = "TestObject")]
public class TestObject : ITestObject
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Value { get; set; }
}

public class TestApp
{
    public void Run()
    {
        IList<ITestObject> a = new List<ITestObject>();
        a.Add(new TestObject() { Id = 1, Value = "A" });
        a.Add(new TestObject() { Id = 2, Value = "B" });

        IList<ITestObject> b = Copy(a);

        // a is a List<T> while b is a readonly T[]
        Debug.WriteLine(a.GetType().FullName);
        Debug.WriteLine(b.GetType().FullName);
    }

    public IList<ITestObject> Copy(IList<ITestObject> list)
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(IList<ITestObject>), new Type[] { typeof(TestObject) });
        using (Stream stream = new MemoryStream())
        {
            serializer.WriteObject(stream, list);
            stream.Seek(0, SeekOrigin.Begin);
            IList<ITestObject> clone = (IList<ITestObject>)serializer.ReadObject(stream);
            stream.Close();
            return clone;
        }
    }
}

I'm guessing it's something to do with the fact List<T> isn't listed as a KnownType


Solution

  • Try using a DataContractSerializer(typeof(List<ITestObject>) so that it knows the concrete type