I want de deserialize a bunch of XML messages that share some parts to a concrete class inheriting from a base class.
I have a factory method that creates instances of the concrete classes based on the xml content:
public class MessageFactory
{
static public Message Create(string xml)
{
Message mm = Message.Deserialize(xml);
Message concreteMessage = null;
switch (mm.MessageHeader.MessageTypeCode)
{
case "010":
concreteMessage = MM010.Deserialize(xml);
break;
case "020":
concreteMessage = MM020.Deserialize(xml);
break;
}
return concreteMessage;
}
}
where the Deserialize method is implemented in the Message base class like this:
public static Message Deserialize(string xml)
{
System.IO.StringReader stringReader = null;
try
{
stringReader = new System.IO.StringReader(xml);
return ((Message)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
EDIT: previous method was incorrect, fixed
Obviously this does not work since the Deserialize method always returns a base class instance. What would be the best way to define the Deserialize (and Serialize) methods at the base class so that it actually returns instances of the concrete classes?