InvalidDataContractException is an invalid collection type since it have DataContractAttribute

cls71 picture cls71 · Mar 29, 2014 · Viewed 7.4k times · Source

I have this code:

[DataContract]
class MyData
{
    private Int32 dato1;
    [DataMember]
    public Int32 Dato1
    {
        get { return dato1; }
        set { dato1 = value; }
    }

    public MyData(Int32 dato1)
    {
        this.dato1 = dato1;
    }
    public MyData()
    {
        this.dato1 = 0;
    }
}

[DataContract]
class MyCollection2 : List<MyData>
{
    public MyCollection2()
    {
    }

}

Then I try to serialize one object of MyCollection2 with:

MyCollection2 collec2 = new MyCollection2();
collec2.Add(new MyData(10));
DataContractSerializer ds = new DataContractSerializer(typeof(MyCollection2));
using (Stream s = File.Create(dialog.FileName))
{
    ds.WriteObject(s, collec2);
}

Then I get the next exception:

InvalidDataContractException is an invalid collection type since it have DataContractAttribute

However, if I use the next class (doesn't inherit directly from List, instead has a List member):

[DataContract]
class MyCollection1
{
    [DataMember]
    public List<MyData> items;

    public MyCollection1()
    {
        items = new List<MyData>();
    }

}

Here Serialization works ok. Do you know why ?. Thanks very much.

Answer

mok picture mok · Mar 29, 2014

Use [CollectionDataContract(...)] instead of [DataContract]. For more details see here.

For full details see here.