Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - set object property considering data type

I already found out that it is possible to set the value of a property using reflection: Set object property using reflection

But my problem is that my data exists only as string. Therefore of course I always get an exception because it is not the right type.

Is there a way of automatically trying to parse the string to the according type (DateTime, int, decimal, float)?

Below is the code I'm using:

Type myType = obj.GetType();
PropertyInfo[] props = myType.GetProperties();

foreach (PropertyInfo prop in props)
{
   setProperty(obj, prop, data[prop.Name]);
}

data is a simple associative array that contains the data as string. These data are supposed to be mapped into obj.

like image 552
Kuepper Avatar asked Mar 09 '11 00:03

Kuepper


People also ask

How does reflection set property value?

To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.

How to set value to get Property in c#?

To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.

Why reflection is used in C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is GetProperty C#?

GetProperty(String, BindingFlags) Searches for the specified property, using the specified binding constraints. public: virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr); C# Copy.


2 Answers

You can use the Convert class:

   var value = Convert.ChangeType(data[prop.Name], prop.PropertyType);
   setProperty(obj, prop, value);
like image 121
Mark Cidade Avatar answered Sep 22 '22 14:09

Mark Cidade


You should be able to use the TypeConverter:

var converter = TypeDescriptor.GetConverter(prop.PropertyType);
var value = converter.ConvertFromString(data[prop.Name]);
setProperty(obj,prop,value);
like image 39
BFree Avatar answered Sep 24 '22 14:09

BFree