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.

KingOfBabu
  • 409
  • 3
  • 21
  • 2
    Possible duplicate of [How do I use reflection to call a generic method?](http://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – MakePeaceGreatAgain Jun 03 '16 at 12:05

1 Answers1

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);
Dennis
  • 37,026
  • 10
  • 82
  • 150
  • 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. – MakePeaceGreatAgain Jun 03 '16 at 12:08
  • @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. :) – Dennis Jun 03 '16 at 12:13
  • 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 Jun 03 '16 at 12:19
  • 2
    @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`). – Dennis Jun 03 '16 at 12:25
  • Ok, this is better now ! I will use reflection, thanks :) – KingOfBabu Jun 03 '16 at 12:27