Code Snippet: PrintObject

Written by Troy Howard

10 July 2007

Following up on the same idea as the ListEnum code snippet, this is a method I often use to print the properties of an object to the console.

I write a number of small command-line utilities and typically, I create a "property bag" type of object that contains all of the possible command-line options. Just before execution, I like to display the options to the user, so that they know that the program knows what they meant by the command-line options.

Here's the code that does that:

private static void printObject(object obj) {

  PropertyInfo[] pia = obj.GetType().GetProperties(); 

  foreach (PropertyInfo pi in pia) {
    Console.WriteLine( pi.Name.PadRight(16, ' ') +
    ": " +
    pi.GetValue(obj, null).ToString()); 
  }
}

This could, of course, be used for any scenario where you want to inspect the values of the properties on an object. If you were so inclined, this could easily be expanded to have a lot more detail, handle arrays, print the type name of the object, etc.. I have various permutations of this method that do some or all of that as needed. I have considered turning this into a class with all those fiddly bits configurable, but haven't gotten around to it yet… If I ever do, I'll post it here!