A collection of learnings and opinions.

Tuesday, February 10, 2009

Listing the properties of an object

Sometimes you just want to print out the state of some reasonably rich object (for logging or GUI mock-up or whatever). This code gives you a PropertyGetter class with two easy-to-use static methods. listProperties returns a name: value string listing of the properties on the input object, for easy logging.

If you want the object's properties as a list of properties you can get that as well.

NB: This simple class does not recurse through complex objects, so you will only ever get the top-level of a property.

Code:

using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Code_Examples {
class PropertyGetter {
public static string listProperties(object someObject) {
StringBuilder sb = new StringBuilder();

List<pair> props = getProperties(someObject);

foreach (Pair prop in props) {
sb.AppendLine(prop.Name + ": " + prop.Value);
}
return sb.ToString();
}

public static List<pair> getProperties(object someObject) {
List<pair> dic = new List<pair>();

PropertyInfo[] props = someObject.GetType().GetProperties();
foreach (PropertyInfo prop in props) {
Pair t = new Pair {
Name = prop.Name,
Value = prop.GetValue(someObject, null)
};
dic.Add(t);
}
return dic;
}
}

public class Pair {
public string Name {
get;
set;
}
public object Value {
get;
set;
}
}
}