Last post Sep 13, 2019 03:51 PM by mgebhard
Sep 13, 2019 12:17 PM|EssCee|LINK
I have a couple of separate XMLs being requested depending on the requirement i.e.
First request - Get all stores
Second request - For each store get all employees
Third request - For all employees get their personal details
For each XML I'm generating a class from an online tool, so i can deserialise the XML. I have one procedure which makes the call and then i deserialise the XML with the below
private void GetData(string strXML, Type XmlType)
XmlSerializer serializer = new XmlSerializer(typeof(Stores));
StringReader rdr = new StringReader(strXml);
Stores resultingMessage = (Stores)serializer.Deserialize(rdr);
This works as expected, the class generates the data etc but i want to be able to reuse this code and pass in a different type (so
Stores, would then have the relevant XML passed in but this time i would pass in
Employees type). I added Type XmlType and tried to pass that in but it throws a compile error "The type or namespace name 'XmlType' could not be found (are you missing a using directive or an assembly reference?)".
Is it possible to have a different type passed in or a better way to write this?
Sep 13, 2019 12:38 PM|EssCee|LINK
Just figured out i could do
if (XmlType == typeof(Stores))....
If anyone has any better ways im happy to mark as answer
Sep 13, 2019 02:29 PM|mgebhard|LINK
Generic methods solve this problem.
private static T GetData<T>(string strXML)
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringReader rdr = new StringReader(strXML);
T obj = (T)serializer.Deserialize(rdr);
Sep 13, 2019 03:44 PM|EssCee|LINK
Great this looks much better.
Sep 13, 2019 03:51 PM|mgebhard|LINK
Note the different property within each class - i thought this would error but it didnt, does this structure look ok as is or could i make a different design decision here? My concern here is how would the program know which Store class i am referring to? I
know i can test this but in case i can avoid any bad designs it would help
There are two options; namespace or inheritance.
A unique namespace make the type unique. With inheritance the class names are unique while the classes share members.