How to use DataContract with inheritance? Will code below work?
[DataContract]
public class ConsoleData
{
[DataMember]
public String Description { get; set; }
}
[DataContract]
public class SomeData : ConsoleData
{
[DataMember]
public int Volume { get; set; }
......
Yes, that would work.
The
DataContractAttributehasInheritedset to false, so it is necessary to apply the attribute to both the child class and the parent class (as you have done in the question).You would need to use the
KnownTypeattribute if you want to use your data contracts with polymorphism.For example
If you invoked the method like so:
Then the deserializer on the service end will not know that it’s an instance of
SomeData, just an instance ofConsoleDatawhich it was expecting.The way to fix this is to register the
SomeDataclass as a known type of theConsoleData.