25 October, 2006

Get/Set Properteis Using Reflection

Just sometihing I had to do yesterday, getting and setting properties using System.Reflection in .Net, tought I share.

Get property

Assembly assembly = Assembly.LoadFrom(assemblyPath);
/* ... */
object o = Activator.CreateInstance(t);

PropertyInfo propertyInfo = t.GetProperty("CustomProp");
object val = propertyInfo.GetValue(o, null);

Set Property

Assembly assembly = Assembly.LoadFrom(assemblyPath);
/* ... */
object o = Activator.CreateInstance(t);

PropertyInfo propertyInfo = t.GetProperty("propertyName");
propertyInfo.SetValue(o, "propertyValue", null);

Tags: