C# Inhieriting DataContract Derived Types
        Posted  
        
            by dsjohnston
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by dsjohnston
        
        
        
        Published on 2010-05-20T17:44:37Z
        Indexed on 
            2010/05/20
            17:50 UTC
        
        
        Read the original article
        Hit count: 613
        
I've given a fair read through msdn:datacontracts and I cannot find a out why the following does not work. So what is wrong here? Why isn't ExtendedCanadianAddress recognized by the datacontract serializer?
Type 'XYZ.ExtendedCanadianAddress' with data contract name 'CanadianAddress:http://tempuri.org/Common/Types' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Given:
namespace ABC  
{  
 [KnownType(typeof(Address))] 
 public abstract class Z  
 {
   //stuff
   //method that adds all types() in namespace to self
 }
 [KnownType(typeof(CanadianAddress))]  
 [DataContact(Name = "Address", Namespace = "http://tempuri.org/Types")]  
 public class Address : Z
 {}
 [DataContract(Name = "CanadianAddress", Namespace = "http://tempuri.org/Types")]
 public class CanadianAddress : Address
 {}
}
namespace XYZ
{
 [KnownType(typeof(ExtendedCanadianAddress))
 [DataContact(Name = "Address", Namespace = "http://tempuri.org/Types")] 
 public class ExtendedAddress : Address
 {
   //this serializes just fine
 }
 [DataContact(Name = "CanadianAddress", Namespace = "http://tempuri.org/Types")] 
 public class ExtendedCanadianAddress : CanadianAddress
 {
   //will NOT serialize
 }
}
© Stack Overflow or respective owner