0

Can I use a string to type a Templated method in C#?

I would like to do something like this (Juste an example code)

string str = "MyProject.MyType"; dynamic obj = jsonObject.ToObject<str>();

I tried to use Type.GetType() to get the type from my string, but it doesn't work too.

Sylvain GIROD
  • 836
  • 1
  • 11
  • 23
  • It is really unclear what you want. Is your goal to get an instance of 'MyType'? Where does the idea of a list come from? – Loofer Jan 27 '16 at 14:25
  • Don't use generic method if you don't know type at compile time. There should be another non-generic method (or completely another approach) to specify type as parameter, e.g. `jsonObject.ToObject(Type.GetType(str));` – Sinatr Jan 27 '16 at 14:27
  • Nop, i know that part, but i would like to know how to use a string as a type. – Sylvain GIROD Jan 27 '16 at 14:31
  • @Sinatr I tried this, but got an error (`Operator '<' cannot be applied to operands of type 'method group' and 'Type'`) – Sylvain GIROD Jan 27 '16 at 14:34
  • @Loofer I've got a terrible english, sorry for that. I have a string like `"Project.ObjectToDeserializeType"` and I need to use it for my `jsonObject.ToObject()` method – Sylvain GIROD Jan 27 '16 at 14:37
  • What is `jsonObject`? Json.Net? You have to use [this](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject_1.htm) method (not sure, but should give you idea) (where you pass type **as parameter**) and not [generic method](https://msdn.microsoft.com/en-us/library/twcad0zb.aspx). Generic method (one with `<>`) require to know type in advance as a constant (you can use reflection, but it's another *complicated* story). You want to pass it as parameter, so you can not use `ToObject<>`. – Sinatr Jan 27 '16 at 14:40
  • @Sinatr You solved my problem, thank you ! – Sylvain GIROD Jan 27 '16 at 15:08

0 Answers0