Melursus Melursus - 1 year ago 80
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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download