Click here to Skip to main content
15,443,549 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have function which Deserialize a xml its generic type method.

code is :

C#
public static T DeserializeFromXml<t>(string xml)
        {
            T result;
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextReader tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }


i can use this method in my application.
Now Problem is that i want to send T at runtime where i have to decide Type of T.

if i do :
C#
var type = Obje1.GetType();
DeserializeFromXml<type>(FileXml) // it gives error


2nd option :
C#
System.Type type = Obje1.GetType();
DeserializeFromXml<type>(FileXml) // it gives error


can any bodey help to pass Type at runtime?
i dont want to use if else or switch case like
C#
if (obj1.GetType() == typeof(int))


Thanks in Advance.
Posted
v2

1 solution

To use DeserializeFromXml<T>() you must supply the type at compile time :
C#
public class mytype { ... }

DeserializeFromXml<mytype>(FileXml);
</mytype>

If you don't know the type at compile time then you should use :
C#
public static object DeserializeFromXml(Type t, string xml)
        {
            object result;
            XmlSerializer ser = new XmlSerializer(t);
            using (TextReader tr = new StringReader(xml))
            {
                result = ser.Deserialize(tr);
            }
            return result;
        }

DeserializeFromXml(Obje1.GetType(), FileXml);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900