Serializing abstract classes to XML
Digg it: http://digg.com/programming/Serializing_abstract_classes_to_XML_in_c
It is often useful to have abstract classes with several derived types to allow use of strongly typed lists and the such.
For example you might have a DocumentFragment class which is abstract and two concrete classes called TextDocumentFragment and CommentDocumentFragment (this example from Willis).
This allows the creation of a List<DocumentFragment> property which can contain objects only of those two types.
If you attempt to create a WebService that returns this list you get an error but this is easy to get around with the code below....
[Serializable()]
[System.Xml.Serialization.XmlInclude(typeof(TextDocumentFragment))]
[System.Xml.Serialization.XmlInclude(typeof(CommentDocumentFragment))]
public abstract class DocumentFragment {
...}
The XmlInclude attributes tell the class that it might be serialized to those two derived classes.
This generates an attribute in the DocumentFragment element specifying the actual type, as below.
<DocumentFragment xsi:type="TextDocumentFragment">
Any additonal properties specific to the derived class will also be included using this method.