C# dynamically set property

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

Tags:

C#

Methods