How to pass in Type RRS feed

  • Question

  • User-284642143 posted

    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?

    Friday, September 13, 2019 12:17 PM


All replies

  • User-284642143 posted

    Just figured out i could do 

    if (XmlType == typeof(Stores))....

    If anyone has any better ways im happy to mark as answer

    Friday, September 13, 2019 12:38 PM
  • User475983607 posted

    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);
                return obj;


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 2:29 PM
  • User-284642143 posted

    Great this looks much better.

    Friday, September 13, 2019 3:44 PM
  • User475983607 posted

    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.

    Friday, September 13, 2019 3:51 PM