C# dynamically set property [duplicate]

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!


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


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);
    }
}

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); 
} 

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

PropertyInfo propertyInfo = objName.GetType().GetProperty(propertyName);
propertyInfo.SetValue(objName, value, null);