When I try to serialize my own class that is derived from ReadOnlyCollection I get the error:
Type 'MyReadOnlyCollection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with CollectionDataContractAttribute attribute is an invalid collection type since it does not have a default constructor.
Now the error makes sense, it's true I do not have a default constructor. However I am able to Serialize a ReadOnlyCollection using the DataContractSerializer even though ReadOnlyCollection does not have a parameterless default constructor.
// OK
ReadOnlyCollection<string> readOnlyCollection = new ReadOnlyCollection<string>(new List<string> { "a", "b", "c" });
string result1 = Serialize(readOnlyCollection);
// Throws InvalidDataContractException
MyReadOnlyCollection<string> myReadOnlyCollection = new MyReadOnlyCollection<string>(new List<string> { "a", "b", "c" });
string result2 = Serialize(myReadOnlyCollection);
public static string Serialize(object o)
{
var serializer = new DataContractSerializer(o.GetType());
var stringBuilder = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
{
serializer.WriteObject(xmlWriter, o);
}
return stringBuilder.ToString();
}
[CollectionDataContract]
public class MyReadOnlyCollection<T> : ReadOnlyCollection<T>
{
public MyReadOnlyCollection(IList<T> list) : base(list)
{
}
}
Two questions:
Update: I've added my derived class above
How should I serialize my derived class correctly?
to serialize your derived class correctly you should do something like this
[DataContract]
public class MyReadOnlyCollection<T>:ReadOnlyCollection<T>
{
public MyReadOnlyCollection(IList<T> list) : base(list)
{
}
}
EDIT
You cannot use [CollectionDataContract]
because it does not fully meet collection type requirements as the Add method is missing so the type is not considered as a collection type
For more information Collection Types in Data Contracts