Tuesday, August 15, 2006
Retrieving class property values via reflection
Recently I was implementing some logging code for some legacy C# classes that contained many public properties. Instead of implementing each property in the overriden ToString() of the class, I decided to use reflection to get the list of properties and print out their values:
The code first gets the Type of the class that contains the properties. Then it retrieves an array of PropertyInfo objects that contains each property name and type. The GetValue method of the PropertyInfo class is used to retrieve the value of the property. It takes two arguments; the first argument is the pointer to the class that contains the property, and the second value is an object array in the case that the property is an indexed property (stores an indexed array). if the class does not contain any indexed properties, you can pass in null for the second parameter.
public override string ToString()
{
StringBuilder sb = new StringBuilder();
Type t = this.GetType();
PropertyInfo[] pInfo = t.GetProperties();
sb.Append(t.ToString() + "\r\n");
foreach (PropertyInfo p in pInfo)
{
string fmt = string.Format("{0} = {1}", p.Name, p.GetValue(this, null));
sb.Append(fmt + "\r\n");
}
return sb.ToString();
}
The code first gets the Type of the class that contains the properties. Then it retrieves an array of PropertyInfo objects that contains each property name and type. The GetValue method of the PropertyInfo class is used to retrieve the value of the property. It takes two arguments; the first argument is the pointer to the class that contains the property, and the second value is an object array in the case that the property is an indexed property (stores an indexed array). if the class does not contain any indexed properties, you can pass in null for the second parameter.