Say I have a couple of basic objects like so:
[Serializable]
public class Base
{
public string Property1 { get; set; }
public int Property2 { get; s
Use the [XmlInclude]
attribute on your base class to tell the XML serializer about derived classes, so it can figure out what to create. Your last code snippet should then work correctly.
As far as I know, there is no simplier way to do this.
I personally prefer a more generic solution (as I have to serialize a lot of various classes in my code): to keep type name serialized together with the value.
You can take a look at this question for some details: Serialise to XML and include the type of the serialised object
You can read the XML file's root node and instead of using a switch statement, you can write your code like this -
Type yourType = Type.GetType("Your Type");
XmlSerializer xs = new XmlSerializer(yourType);
I don't think there's any way other than reading the XML because if you don't know the type, you can't do anything.