Tuesday, November 10, 2009

Use Reflection to Get and Set Properties on a class


Sometimes it is useful to access a property on a class that you may or may not have created. Use the code below to set or get a value by name for any class.

using System;
using System.Data;
using System.Configuration;
using System.Reflection;

namespace MyApp
{

public class ReflectionHelper
{
public ReflectionHelper()
{

}

public static Object GetProperty(System.Object obj, System.String propertyName)
{

if (propertyName == null)
{
throw new System.ArgumentException("No name specified");
}

PropertyInfo pi = obj.GetType().GetProperty(propertyName);

if (pi == null)
{
throw new Exception("Object does not have a property named: " + propertyName);
}

return pi.GetValue(obj, null);

}

public static void SetProperty(System.Object obj, System.String propertyName, System.Object propertyValue)
{
if (obj == null)
{
throw new System.ArgumentException("No target specified");
}
if (propertyName == null)
{
throw new System.ArgumentException("No name specified");
}

PropertyInfo pi = obj.GetType().GetProperty(propertyName);

if (pi == null)
{
throw new Exception("Object does not have a property named: " + propertyName);
}

pi.SetValue(obj, propertyValue, null);

}
}
}

No comments: