Is there a way in C# where I can use reflection to set an object property?
Ex:
MyObject obj = new MyObject();
obj.Name = \"Value\";
Or you could wrap Marc's one liner inside your own extension class:
public static class PropertyExtension{
public static void SetPropertyValue(this object obj, string propName, object value)
{
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
}
and call it like this:
myObject.SetPropertyValue("myProperty", "myValue");
For good measure, let's add a method to get a property value:
public static object GetPropertyValue(this object obj, string propName)
{
return obj.GetType().GetProperty(propName).GetValue (obj, null);
}
You can also access fields using a simillar manner:
var obj=new MyObject();
FieldInfo fi = obj.GetType().
GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)
With reflection everything can be an open book:) In my example we are binding to a private instance level field.
Reflection, basically, i.e.
myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);
or there are libraries to help both in terms of convenience and performance; for example with FastMember:
var wrapped = ObjectAccessor.Create(obj);
wrapped[property] = "Bob";
(which also has the advantage of not needing to know in advance whether it is a field vs a property)
Yes, using System.Reflection
:
using System.Reflection;
...
string prop = "name";
PropertyInfo pi = myObject.GetType().GetProperty(prop);
pi.SetValue(myObject, "Bob", null);