How to dynamically cast an object of type string to an object of type T

c#, casting, generics

Solution

You can use `Convert.ChangeType` :

object value = Convert.ChangeType(stringValue, destinationType);

Problem

I have this XML document ``` <AdditionalParameters> <PublishToPdf Type ="System.Boolean">False</PublishToPdf> </AdditionalParameters> ``` in my code and I'm trying to build an array of arguments containing the `<PublishToPdf>` node. ``` object test = (object) ((typeof(publishNode.Attributes["Type"].value)) publishNode.InnerText); ``` This breaks at compile time of course. I can't figure out how to cast the `publishNode.InnerText('false')` to a runtime defined object of type specified in the XML file and store it in an object (which will conserve the type).

Original source