5

i wrote this method in order to convert a xml string into the object:

private object Deserializer(Type type)
{
    object instance = null;
    try
    {
        XmlSerializer xmlSerializer = new XmlSerializer(type);
        using (StringReader stringreader = new StringReader(somestring))
        {
            instance = (type)xmlSerializer.Deserialize(stringreader);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return instance;
} 

but here:

instance = (type)xmlSerializer.Deserialize(stringreader);

this error shows up: The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?) how can i fix it?

Mohammad
  • 2,724
  • 6
  • 29
  • 55
  • 2
    The compiler tells you already what is wrong: The type `type` you are casting your instance to, does not exist. Are you sure you are using the correct cast? – DerApe Aug 04 '15 at 07:14

2 Answers2

11

You canno't cast to "type" you need to specify the exact type like this (for string):

(string)xmlSerializer.Deserialize(stringreader);

Maybe consider using generic function like this:

private T Deserializer<T>()
{
    T instance = null;
    try
    {
        var xmlSerializer = new XmlSerializer(typeof(T));
        using (var stringreader = new StringReader(somestring))
        {
            instance = (T)xmlSerializer.Deserialize(stringreader);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return instance;
} 

and than call the function like this:

var instance = xmlSerializer.Deserialize<SomeType>();

if you want to specify the type only in runtime you can use:

instance = Convert.ChangeType(xmlSerializer.Deserialize(stringreader), type);
Guy Levin
  • 1,230
  • 1
  • 10
  • 22
3

But what is a Type is class that u made or what ?

Maybe u want do to :

private object Deserializer<T>(T type)

Edit Try this :

private static T LoadData<T>() where T : new ()
    {
        using (var reader = new StreamReader(@_path))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            return (T) xmlSerializer.Deserialize(reader);
        }

    }
Aht
  • 583
  • 4
  • 25