52

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
  • 2,008
  • 4
  • 26
  • 31
  • @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

88

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

josejuan
  • 9,338
  • 24
  • 31
47

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
  • 80,725
  • 18
  • 167
  • 237
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,159
  • 4
  • 32
  • 53
harriyott
  • 10,505
  • 10
  • 64
  • 103
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,627
  • 19
  • 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
  • 60,939
  • 11
  • 97
  • 136