0

I need to use this method :

public T DeserializeFromXmlString<T>(string xmlString)
{
    var serializer = new XmlSerializer(typeof(T));
    using (TextReader reader = new StringReader(xmlString))
    {
        return (T)serializer.Deserialize(reader);
    }
}

And to use it, I need to know the generic type T. Imagine that I have a class "Apple". I will use it like this:

var myapple= DeserializeFromXmlString<Apple>(someXmlString);

But I need to be able to remove this <Apple> and replacing it by something else considering that I have the string "Apple".
The goal is to convert a string to be able to use it in this method as a generic type T.

1

1 Answer 1

2

Re-design your API to support non-generic cases:

public object DeserializeFromXmlString(Type targetType, string xmlString)
{
    var serializer = new XmlSerializer(targetType);
    using (TextReader reader = new StringReader(xmlString))
    {
        return serializer.Deserialize(reader);
    }
}

public T DeserializeFromXmlString<T>(string xmlString)
{
    return (T)DeserializeFromXmlString(typeof(T), xmlString);
}

Load type from string and use non-generic API:

var targetType = Type.GetType("YourTypeName", true);
var deserializedObj = DeserializeFromXmlString(targetType, yourXmlString);
Sign up to request clarification or add additional context in comments.

5 Comments

This however won´t return a strongly typed instance of T if we don´t know the type at compile-time which is what OP wants - as far as I see.
@HimBromBeere: absolutely. But, if we know type at compile-time, we've got a type instead of type name. IMO, it is strange to talk about type safety in context of type name usage. :)
Ok, thanks this help ! But what can I do now if I want to get the value of a xml element now ? Before, I could just do myApple.color for example
@KingOfBabu: it looks like you're talking about two mutual exclusive use cases. To be able to write myApple.Color, you need to know about Apple type at compile-type; and if you know about Apple, then you can use generic method and don't need type name. Assuming, that Apple is unknown at compile-time, you need non-generic method, but you can't write myApple.Color in this case. Your options will be: a) dynamic; b) reflection; c) casting to some base type, which is known statically (e.g. Fruit).
Ok, this is better now ! I will use reflection, thanks :)

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.