C# – 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?

Best Solution

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