Search code examples
c#interfacexmlserializer

Extract some fields from a data class for serialization


I would like serialize some stuff. For now the program serializes my whole data class with 15 fields in it and writes it in a txt-file. I would like to split serialization of my data class in two parts: it should serialize and write the first 8 fields in txtFile_A, and on other occasion serialize und write the second 7 fields in txtFile_B.

I tried to split my data class with the help of interfaces.

public class PuppiesAndKittens: IPuppies
{
    public bool PuppyEats { get; set; }
    public bool PuppyBarks { get; set; }
    //...
}

public interface IPuppies
{
    bool PuppyEats { get; set; }
    bool PuppyBarks { get; set; }
    //....
}

Serialization part:

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
    XmlSerializer s;

    s = new XmlSerializer((PuppiesAndKittensInstance as IPuppies).GetType());

    // I would expect here the type of IPuppies, but the type is still PuppiesAndKittens. It contains all 15 fields and not the needed 8 for the txtfile_A

    s.Serialize(sw, (PuppiesAndKittensInstance as IPuppies));
}

After the serialization I write this information down to a txtfile.

The question is, if this is generally possible and I miss something in the code? I have other options to solve the problem, which are less preferable.


Solution

  • Implementing an interface alone does not affect the serialization process because the XmlSerializer uses the actual type of the object being serialized, not the interface type. Therefore, casting PuppiesAndKittensInstance to IPuppies does not change the serialization behavior. One option would be to create a separate class for each field you want to serialize and populate those with the necessary fields from your original class.