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?

1
  • 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? Commented Aug 4, 2015 at 7:14

2 Answers 2

12

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);
Sign up to request clarification or add additional context in comments.

1 Comment

The try block is useless, you need a string parameter, the T variable is useless.
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);
        }

    }

2 Comments

Type is most probably System.Type. And I think your solution would be better if it returned T instead of object.
Y my bad i try to write it to fast. I edited my comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.