Monday, 3 January 2011

Dump object state to string

Question:
I want to dump the members and properties of an object to the log to see the objects state.




Answer:
The easiest way to do this, is to use dot.Net Reflection.

// extension method
public static string DumpObject(this object obj)
{
 StringBuilder sb = new StringBuilder();
 if (obj != null)
 {
  foreach (System.Reflection.PropertyInfo prop in obj.GetType().GetProperties())
  {
   sb.AppendLine(prop.Name + " : [" + prop.GetValue(obj, null) + "]");
  }
 }
 return sb.ToString();
}

No comments: