When I have the following classes and I try to serialize a ConcreteClass
instance with DataContractSerializer.WriteObject(..)
I get an InvalidDataContractException
.
public abstract class AbstractClass
{
protected AbstractClass(string text) { }
}
public class ConcreteClass : AbstractClass
{
public ConcreteClass() : base("text") { }
}
The serializer is instantiated with new DataContractSerializer(typeof(ConcreteClass)
.
Using XmlSerializer makes no problems.
Now when adding public AbstractClass() {}
both serializers work.
So why does the DataContractSerializer requires abstract base classes to have a parameterless contructor? Here it is stated that types can be serialized which "have a constructor that does not have parameters" which is true for ConcreteClass. I also added some code to this required constructor and i don't think that it is ever called during the serialization process.
The complete Exception says:
System.Runtime.Serialization.InvalidDataContractException : Type AbstractClass' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.
It even works if i leave the parameterless constructor and instead use the proposed attribute. So why is there a difference and why there is an attempt to serialize an abstract class? Of course there could be things like properties in the abstract class but should't these be serialized together with a ConcreteClass instance (which inherit such things)?
Edit:
My exact code:
namespace SerilizationTest
{
public abstract class AbstractClass
{
public string StringProperty { get; set; }
//This constructor is required (although never called).
//If not present we get "InvalidDataContractException :
//Type AbstractClass cannot be serialized"
public AbstractClass()
{
Console.WriteLine("We won't see this.");
}
public AbstractClass(string text)
{
StringProperty = text;
}
}
public class ConcreteClass : AbstractClass
{
public ConcreteClass() : base("text") { }
}
class Program
{
static void Main()
{
var serializer = new DataContractSerializer(typeof(ConcreteClass));
var memStream = new MemoryStream();
serializer.WriteObject(memStream, new ConcreteClass());
memStream.Seek(0, SeekOrigin.Begin);
var deserializedObj = (ConcreteClass)serializer.ReadObject(memStream);
Console.WriteLine(deserializedObj.StringProperty);
}
}
}
abstract class
? Logical error, does not compute. – Louisvillepublic AbstractClass() {}
" i meant adding this line of code into the code from the AbstractClass – Nightshade