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.

Answers


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

For full details see here.


Need Your Help

Explicitly Specifying types for Express' "application, request, response..."

express typescript

I'm working to update a simple NodeJS + ExpressJS app to use TypeScript. I've got it working, but I'm having fits adding some extra data annotations to add extra type checking and code-time autocom...

How to detect input type=file "change" for the same file?

jquery html events cross-browser

I want to fire an event when the user select a file. Doing so with .change event it works if the user changes the file every time.