This code snippet posted below can be used to display all object's property values, by inkoing the ToString() of each property. An usefull implementation could be when you are in need of logging an object's state by writing to a log file all his properties states.
The DisplayObjectProperties static method cycles throught the object's properties and as told before, it calls the ToString() method, which is always implemented since every class is derived from the Object class. Recuirsion is not implemented, the ToString() method will be called only at the first level.
public static class ReflectionHelper
{
public static string DisplayObjectProperties(Object o)
{
StringBuilder sb = new StringBuilder();
System.Type type = o.GetType();
foreach (PropertyInfo p in type.GetProperties())
{
if (p.CanRead)
{
object obj = p.GetValue(o, null);
if (obj != null)
{
sb.AppendLine(String.Concat("-Property name: ", p.Name ));
sb.AppendLine(String.Concat("-Property value:", obj.ToString()));
sb.AppendLine();
}
else sb.Append(String.Concat(p.Name, " # Value is null"));
}
}
return sb.ToString();
}
}
Now immagine that you' ve got this sample class called PersonalAttribute:
public class PersonalAttribute
{
public string AttributeName { get; set; }
public string AttributeValue { get; set; }
}
An usefull implementation could be:
public class PersonalAttribute
{
public string AttributeName { get; set; }
public string AttributeValue { get; set; }
public override string ToString()
{
return ReflectionHelper.DisplayObjectProperties(this);
}
}
Now, when the ToString() method is invoked in a new PersonalAttribute's istance, the returned string is something similar to:
-Property name: AttributeName
-Property value:SiteName
-Property name: AttributeValue
-Property value:myrocode.com
Remember that using Reflection is slow compared to direct access of a property, field or method. If you are building a complex application, this could be not the best solution for you case.