.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

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds