48

Possible Duplicate:
.Net - Reflection set object property
Setting a property by reflection with a string value

I have an object with multiple properties. Let's call the object objName. I'm trying to create a method that simply updates the object with the new property values.

I want to be able to do the following in a method:

private void SetObjectProperty(string propertyName, string value, ref object objName)
{
    //some processing on the rest of the code to make sure we actually want to set this value.
    objName.propertyName = value
}

and finally, the call:

SetObjectProperty("nameOfProperty", textBoxValue.Text, ref objName);

Hope the question is fleshed out enough. Let me know if you need more details.

Thanks for the answers all!

David Archer
  • 1,948
  • 4
  • 24
  • 30
  • @DavidArcher there is no `rel` keyboard in C#...I take it you mean `ref`? There is no need to pass an object as `ref` unless you intend on changing the actual instance of it. – James Oct 19 '12 at 08:55
  • Indeed, I did mean ref, and yes, I do intend on changing the actual instance. – David Archer Oct 19 '12 at 09:00

5 Answers5

79

objName.GetType().GetProperty("nameOfProperty").SetValue(objName, objValue, null)

josejuan
  • 8,934
  • 21
  • 30
45

You can use Reflection to do this e.g.

private void SetObjectProperty(string propertyName, string value, object obj)
{
    PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
    // make sure object has the property we are after
    if (propertyInfo != null)
    {
        propertyInfo.SetValue(obj, value, null);
    }
}
James
  • 77,877
  • 18
  • 158
  • 228
4

Get the property info first, and then set the value on the property:

PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objName, value, null);
Adam
  • 4,117
  • 4
  • 29
  • 51
harriyott
  • 10,335
  • 10
  • 62
  • 100
4

You can use Type.InvokeMember to do this.

private void SetObjectProperty(string propertyName, string value, rel objName) 
{ 
    objName.GetType().InvokeMember(propertyName, 
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, 
        Type.DefaultBinder, objName, value); 
} 
Ekk
  • 5,529
  • 17
  • 27
2

You can do it via reflection:

void SetObjectProperty(object theObject, string propertyName, object value)
{
  Type type=theObject.GetType();
  var property=type.GetProperty(propertyName);
  var setter=property.SetMethod();
  setter.Invoke(theObject, new ojbject[]{value});
}

NOTE: Error handling intentionally left out for the sake of readability.

Sean
  • 58,802
  • 11
  • 90
  • 132