I am developing an application where I get XML formatted strings so I have to serialize each string in its respective class.
What I want is to create a single method in which I can serialize these xml-formatted strings into their respective object class, obviously passing as a parameter the type of the class to serialize into.
My code:
public Invoice XML(string xml, out string Error)
{
Invoice comprobante = new Invoice();
Error = "";
try
{
XmlSerializer serializer = new XmlSerializer(typeof(Invoice));
StringReader sXML = new StringReader(xml);
comprobante = (Invoice)serializer.Deserialize(sXML);
}
catch (Exception ex)
{
Error = "Error en la Serialización" + ex.Message;
comprobante = new Invoice();
}
return comprobante;
}
Your generic method would look like this:
You need the new() constraint which indicates that the class must have a default constructor: