Thursday, June 3, 2010

Set Instance Property Value through Reflection

This is how you can set object property value using reflection:

Employee emp = new Employee();
PropertyInfo pi = emp.GetType().GetProperty("myPropertyName");
pi.SetValue(emp, "myValue", null);

This is how you read a value:

string value = pi.GetValue(emp, null);

To access all properties of an object:

foreach (PropertyInfo info in emp.GetType().GetProperties()){
    ....
}
Using reflection you can automatically populate a transfer object from a database record if the object property names and types are the same as the record names and types.

An example using a DataReader:

List <employee>list = new List <employee>();
while (dataReader.Read())
{
Employee emp = new Employee();
foreach (PropertyInfo info in emp.GetType().GetProperties())
{
   if (!DBNull.Value.Equals(dr[info.Name]))
      info.SetValue(emp, dr[info.Name], null);
}
list.Add(emp);
}
 
The resulting list will hold Employee records.





No comments:

Post a Comment