Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string (System.String) to type

Tags:

c#

xml

linq

I am trying to create a generic XML to object converter. In other words, the following is my XML

<setting>
   <name>testing</name> 
   <type>System.String</type>
   <defaultObj>TTTT</defaultObj>
</setting>

the type field holds the type of the object its loading back in. This is just the object structure I serailized in. Regardless, I am having an issue converting

System.String

into an actual type variable. So for instance, in order to convert I have the following code:

foreach (XNode node in document.Element(root).Nodes())
{
   T variable = new T(); //where T : new()

   foreach (FieldInfo field in fields)
   {
      field.SetValue(variable, Convert.ChangeType(((XElement)node).Element(field.Name).Value, field.FieldType));
   }

   retainedList.Add(variable);
}

which obtains objects back in a generic way. The algorithm works perfectly until it comes across the Type field. I get a:

Invalid cast from 'System.String' to 'System.Type'.

run time error. From what I can tell it is having an issue directly converting a type identifier (string) directly into a type. I am not sure how to get around this issue, atleast when it comes to keeping things generic and clean. Any ideas? I am sorry if the issue is a bit vague, if you don't quite understand I will try to clarify further. Any help is greatly appreciated!

like image 785
Serguei Fedorov Avatar asked Oct 29 '12 16:10

Serguei Fedorov


2 Answers

You need to convert the string System.String into the type System.String.

You can do that with Type.GetType(string typeName);

For example, the type variable below will have the Type object of System.String.

var type = Type.GetType("System.String");

You can then use that Type in the Convert.ChangeType overload you're using.

Convert.ChangeType(fieldValue, type);
like image 159
ken Avatar answered Sep 18 '22 21:09

ken


Take a look at Type.GetType which has a variety of overloads to maps type specified as string to Type instances.

like image 24
Sean Avatar answered Sep 20 '22 21:09

Sean