Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamically set property [duplicate]

Tags:

methods

c#

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!

like image 292
David Archer Avatar asked Oct 19 '12 08:10

David Archer


3 Answers

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

like image 90
josejuan Avatar answered Sep 22 '22 09:09

josejuan


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);
    }
}
like image 31
James Avatar answered Sep 21 '22 09:09

James


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); 
} 
like image 4
Ekk Avatar answered Sep 24 '22 09:09

Ekk