Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidDataContractException is an invalid collection type since it have DataContractAttribute

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.

like image 492
cls71 Avatar asked Mar 29 '14 11:03

cls71


1 Answers

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

For full details see here.

like image 119
mohsen kamrani Avatar answered Oct 18 '22 21:10

mohsen kamrani