Search code examples
c#inheritanceserializationdatacontractserializerdatacontract

DataContract serialization of an inherited type into a base type


I'm trying to serialize class B as an instance of ita base class A. The DataContractSerializer won't allow me to do that.

An example failing the serialization is as follows:

class Program
{
    [DataContract]
    public class A
    {
        public int Id { get; set; }
    }

    [DataContract]
    public class B : A
    {

    }


    static void Main(string[] args)
    {
        A instance = new B { Id = 42 };

        var dataContractSerializer = new DataContractSerializer(typeof(A));
        var xmlOutput = new StringBuilder();
        using (var writer = XmlWriter.Create(xmlOutput))
        {
            dataContractSerializer.WriteObject(writer, instance);
        }

    }
}

I know that the issue is easily resolved by added the KnownTypes attribute. However I want to keep the class B hidden from the project (not add a reference).

Is it at all possible to achieve what I want? I tried the XmlSerializer but it gave me the same issue (it added the full instance type name in the XML) and is much more clunkier to use.


Solution

  • [DataContract(Name="YouCannotSeeMyName")]
    [KnownTypes(typeof(B))]
    public class B : A
    

    And you will get

    <A itype="YouCannotSeeMyName">
      ...
    </A>