I have a bunch of different DTO classes. They are being serialized into an XML string at one point and shot over to client-side of the web app. Now when the client shoots
If you don't mind generics:
public static T DeserializeFromString(string value)
{
T outObject;
XmlSerializer deserializer = new XmlSerializer(typeof(T));
StringReader stringReader = new StringReader(value);
outObject = (T)deserializer.Deserialize(stringReader);
stringReader.Close();
return outObject;
}
Edit: If you don't know what type of object the XML will translate to you cannot return anything other than an object. You could of course test afterwards what kind of object you just got. One way to do this would probably be to pass all the types of objects that may be deserialized the XmlSerializer
.
public static object DeserializeFromString(string value, Type[] types)
{
XmlSerializer deserializer = new XmlSerializer(typeof(object), types);
StringReader stringReader = new StringReader(value);
object outObject = deserializer.Deserialize(stringReader);
stringReader.Close();
return outObject;
}
Using this method will assume that your object got boxed (you should serialize the same way), which gives you XML like this:
(If you have many types to pass you can use reflection to get them, e.g. using something like Assembly.GetExecutingAssembly().GetTypes()
)