.NET Tip: Display All Fields and Properties of an Object

I'm a huge fan of the visualizers that Visual Studio provides. They provide a wealth of information in a way that does not get in the way and are an invaluable asset when debugging. There are times, however, when looking at objects during an interactive debugging session isn't appropriate. I work with applications that may have multiple things happening on a timed basis as well as data coming in and raising events in a manner that the timing can't be controlled. Sometimes, the act of debugging itself changes that timing and the problem goes away or is masked during an interactive debugging session.

In this situation, I need to dump the state of several objects before and after some event takes place to determine what is happening. I think the easiest way to do this is by using reflection to have an object dump its own state. I have created a static method in a utility class that takes an Object and returns a string including the type of the object as well as the values of all of the object's fields and properties. Here is the method I use:

public static string DisplayObjectInfo(Object o)
{
   StringBuilder sb = new StringBuilder();

   // Include the type of the object
   System.Type type = o.GetType();
   sb.Append("Type: " + type.Name);

   // Include information for each Field
   sb.Append("\r\n\r\nFields:");
   System.Reflection.FieldInfo[] fi = type.GetFields();
   if (fi.Length > 0)
    {
      foreach (FieldInfo f in fi)
      {
         sb.Append("\r\n " + f.ToString() + " = " + f.GetValue(o));
      }
   }
   else
      sb.Append("\r\n None");

   // Include information for each Property
   sb.Append("\r\n\r\nProperties:");
   System.Reflection.PropertyInfo[] pi = type.GetProperties();
   if (pi.Length > 0)
   {
      foreach (PropertyInfo p in pi)
      {
         sb.Append("\r\n " + p.ToString() + " = " +
                   p.GetValue(o, null));
      }
   }
   else
      sb.Append("\r\n None");

   return sb.ToString();
}

The DisplayObjectInfo method first includes the actual type of the object parameter. It then proceeds to get a list of all the object's fields and includes the data type, name, and value of each field. The same is then done for each of the object's properties. The end result is a string that contains the object's type as well as all of its field and property values. You then can do whatever you would like with the string. It could be displayed on a form, in a message box, sent to the event log or to a trace listener. Here, I'll use an example of sending the contents of a GPSLocation object from an earlier tip to the output window.

GPSLocation Location = new GPSLocation(39, -86, 50, 180);
Debug.Print(Util.DisplayObjectInfo(Location));

The results in the output window look like this:

Type: GPSLocation

Fields:
   None

Properties:
   Double Latitude = 39
   Double Longitude = -86
   Int32 Speed = 50
   Int32 Direction = 180

With this type of diagnostic information, it has been much easier for me to debug. Obviously, you could choose to output the results in whatever format and to whatever source works best for you. This type of method also is very useful if you need to dump the state of your objects when an exception occurs. I hope that you find this technique useful and will further investigate how you can use reflection.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Is your sales and operations planning helping or hurting your bottom line? Here are 5 useful tips from the experts at Quintiq to guide you to a better S&OP strategy.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds