Serialization of generic properties Serialization of generic properties xml xml

Serialization of generic properties


I think that the CS0029 compiler error page on MSDN provides the information you're looking for.

Based on how I read this article, your first example works because there is no conversion happening in your class. Because you explicity are passing around an Object there is no conversion that needs to happen and no compiler errors are thrown.

In the second example the type is not known until run time. By specifying multiple XmlElement attributes the compiler thinks that all of these types must be interchangeable. However, since you haven't provided explicit conversions for these the compiler is concerned that a conversion between the two types could be a narrowing conversion and throws the error.


Have you looked at the Generics FAQ page under the "How Do I Serialize Generic Types" question? It may help you out.


The only way to have different serialized elements for different types is to use object or IXmlSerializable.

Unfortunatelly the XmlSerializer cannot access non-public properties. So exposing the item as an object via a second public property allows serialization. I would not use it in real situations, though:

[XmlElement("GetRecord", typeof(GetRecordType))][XmlElement("Identify", typeof(IdentifyType))]public object ItemSerializer{    get { return this.Item; }    set { this.Item = (T)value; }}[XmlIgnore]public T Item//...