5

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

2
  • What problem you get with your current code? Commented Oct 26, 2012 at 7:47
  • @CuongLe it's trying to set the value of a property that belongs to the type Car on an instance of type System.Type which will not work Commented Oct 26, 2012 at 8:43

1 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.