Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically set the value of a property of object instance using reflection?

Tags:

c#

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

like image 365
JL. Avatar asked Oct 26 '12 07:10

JL.


1 Answers

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);
like image 126
Rune FS Avatar answered Nov 01 '22 16:11

Rune FS