views:

2184

answers:

6

So for viewing a current object's state at runtime, I really like what the Visual Studio Immediate window gives me. Just doing a simple

? objectname

Will give me a nicely formatted 'dump' of the object.

Is there an easy way to do this in code, so I can do something similar when logging?

+1  A: 

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...
Ricardo Villamil
+9  A: 

You could base something on the ObjectDumper code that ships with the Linq samples.

Mike Scott
Wow -- great idea. Also, here is this idea as an extension method http://blogs.msdn.com/danielfe/archive/2005/09/22/473018.aspx
Dan Esparza
Doesn't seem to work for XmlDocuments...
John Hunter
+3  A: 

I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:

  private string ObjectToXml(object output)
  {
     string objectAsXmlString;

     System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
     using (System.IO.StringWriter sw = new System.IO.StringWriter())
     {
        try
        {
           xs.Serialize(sw, output);
           objectAsXmlString = sw.ToString();
        }
        catch (Exception ex)
        {
           objectAsXmlString = ex.ToString();
        }
     }

     return objectAsXmlString;
  }

You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.

Bernhard Hofmann
+1  A: 

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

Darryl Braaten
+1  A: 

It might be a little off-topic here, but Darryl Braaten's post reminded me the DebuggerDisplay attribute for object preview in the watch window while debugging.

gius
+1  A: 

I have a T.Dump() extension method that does exactly this, recursively dumps all properties of any type in a nice readable format.

mythz