Set object property using reflection


Is there a way in C# where I can use reflection to set an object property?


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

I want to set obj.Name with reflection. Something like:

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

Is there a way of doing this?

3/27/2019 1:25:45 PM

Accepted Answer

Yes, you can use Type.InvokeMember():

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

This will throw an exception if obj doesn't have a property called Name, or it can't be set.

Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can 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);
5/9/2017 8:22:06 PM

Exper Answer

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)

1/20/2012 2:05:09 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow