Melursus Melursus - 6 months ago 34
C# Question

Set object property using reflection

Is there a way in .NET c# 3.5 I can use reflection to set an object property?


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

I want to set
with reflection. Something like:

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

Is there a way of doing this?


Yes, you can use Type.InvokeMember():

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

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, "MyName", null);