Search code examples
c#inheritancedatacontractknown-types

DataContract with inheritance?


I have a class with a list of objects that is serialized and deserialized:

[DataContract]
public class Manager
{
  [DataMember]
  public BigBase[] enemies;
}

The class with subclasses:

[DataContract]
[KnownType(typeof(Medium))]
[KnownType(typeof(Small))]
public class BigBase
{
    [DataMember]
    public bool isMoving;
}
[DataContract]
public class Medium : BigBase
{
}
[DataContract]
public class Small: BigBase
{
}

Now whats strange when deserializing the enemies array will contain correctly deserialized BigBase classes but each Medium and Small class doesnt have the correct value for isMoving.


Solution

  • You need to put KnownType attribute on Manager:

    [DataContract]
    [KnownType(typeof(Medium))]
    [KnownType(typeof(Small))]
    public class Manager
    {
      [DataMember]
      public BigBase[] enemies;
    }
    

    Because it's the Manager which has an array of BigBase whose elements might be the derived classes as well. So the DataContractSerializer will know what to expect from the array when serializing and deserializing Manager object (and it's all DataMember).