0

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?

vmasanas
  • 503
  • 1
  • 7
  • 18
  • Might you be able to account for subtypes using Generics? [http://stackoverflow.com/questions/3959340/serialize-and-deserialized-derived-classes-from-the-base-class][1] [1]: http://stackoverflow.com/questions/3959340/serialize-and-deserialized-derived-classes-from-the-base-class – csharplova Nov 07 '14 at 17:28
  • Make it Deserialize(Type t, string xml) and call with Message.Deserialize(typeof(MM010), xml). Now you can use the XmlSerializer(Type) constructor. – Hans Passant Nov 07 '14 at 17:40

0 Answers0