Given a basic class definition:
using System.Reflection;
public class Car()
{
public int speed {get;set;}
public void setSpeed()
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(PropertyName );
property.SetValue(type, Convert.ToInt32(PropertyValue), null);
}
}
This code sample is simplified and not using dynamic type conversion, I just want a working sample to set that property on the instance.
Edit: PropertyName and PropertyValue in above code is also simplified.
Thanks in advance
The first argument you pass should be the instance holding the property you wish to set. If it's a static property pass null for the first argument. In your case change the code to:
public void setSpeed()
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(PropertyName );
property.SetValue(this, Convert.ToInt32(PropertyValue), null);
}
for a naïve type conversion you could do
var value = Convert.ChangeType(PropertyValue,property.PropertyType);
property.SetValue(this, value, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With