views:

945

answers:

3

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

Ex :

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

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

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

Is there a way of doing this ?

+5  A: 

Yes, you can use Type.InvokeMember():

using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
    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);
}
Andy
+7  A: 

You can also do:

Type type = target.GetType();

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

prop.SetValue (target, propertyValue, null);

where target is the object that will have its property set.

El Cheicon
I have done this very same thing today. The above works great, obviously a null check should be done on prop before attempting to use it.
Antony Scott
+2  A: 

You can also access fields using a simillar manner:

var obj=new MyObject();
FieldInfo fi = obj.GetType().
  GetField("Name", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(obj,value)

With reflection everything can be an open book:) In my example we are binding to a private instance level field.

JoshBerke