Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 392
LolaRun Avatar asked Sep 23 '09 13:09

LolaRun


3 Answers

You can use Convert.ChangeType :

object value = Convert.ChangeType(stringValue, destinationType);
like image 64
Thomas Levesque Avatar answered Nov 19 '22 12:11

Thomas Levesque


You can't do exactly what you're trying to do. First, the typeof keyword does not allow for dynamic evaluation at runtime. There are means by which to do this using reflection, with methods like Type.GetType(string), but the Type objects returned from these reflective functions can't be used for operations like casting.

What you need to do is provide a means of converting your type to and from a string representation. There is no automatic conversion from any arbitrary type. For your example, you can use bool.Parse or bool.TryParse, but those are specific to the bool type. There are similar methods on most primitive types.

like image 35
Adam Robinson Avatar answered Nov 19 '22 10:11

Adam Robinson


The simple solution, assuming there is a limited number of possible types;

object GetValueObject(string type, string value)
{
  switch (type)
  {
    case "System.Boolean":
      return Boolean.Parse(value);
    case "System.Int32":
      return Int32.Parse(value);
    ...
    default:
      return value;
  }
}  

var type = publishNode.Attributes["Type"].value;
var value = publishNode.InnerText;
var valueObject = GetValueObject(type, value);
like image 2
Digitalex Avatar answered Nov 19 '22 11:11

Digitalex