Coder Perfect

Set object property using reflection


Is there a way to set an object property using reflection in C#?


MyObject obj = new MyObject();
obj.Name = "Value";

I’d like to use reflection to set obj.Name. Something along these lines:

Reflection.SetProperty(obj, "Name") = "Value";

Is there a way to make this happen?

Asked by Melursus

Solution #1

Yes, Type.InvokeMember() can be used:

using System.Reflection;
MyObject obj = new MyObject();
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder, obj, "Value");

If obj doesn’t have or can’t set a property called Name, an exception will be thrown.

Another option is to obtain the property’s metadata and then set it. This will enable you to check for the property’s existence and confirm that it may be set:

using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
    prop.SetValue(obj, "Value", null);

Answered by Andy

Solution #2

You could also:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

where target is the object whose property will be changed.

Answered by El Cheicon

Solution #3

Reflection, basically, i.e.

myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);

or there are libraries that can aid with both convenience and performance, such as FastMember:

var wrapped = ObjectAccessor.Create(obj); 
wrapped[property] = "Bob";

(which also has the advantage of avoiding the need to know whether it’s a field or a property ahead of time)

Answered by Marc Gravell

Solution #4

Alternatively, you might encapsulate Marc’s one-liner in 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 rename it as follows:

myObject.SetPropertyValue("myProperty", "myValue");

Let’s throw in a method to obtain the value of a property for good measure:

public static object GetPropertyValue(this object obj, string propName)
        return obj.GetType().GetProperty(propName).GetValue (obj, null);

Answered by Erik K.

Solution #5

Yes, using System.Reflection:

using System.Reflection;


    string prop = "name";
    PropertyInfo pi = myObject.GetType().GetProperty(prop);
    pi.SetValue(myObject, "Bob", null);

Answered by D Stanley

Post is based on