This is a mirror of official site: http://jasper-net.blogspot.com/

Dumping .NET classes to debug output

| Thursday, April 22, 2010
Introduction

The good old problem: how to find a variable value during code execution? Debuggers with breakpoints and watch windows are great, but only if the program can be stopped in the right moment in the right spot. Unfortunately, conditions are not always that ideal and dumping needed values to a log file or console, for future analysis, is a more realistic option.

Another common scenario is a simple debugging or run-and-forget utility that needs to produce human readable output with minimal coding. Such tool is not intended for non-technical users and beautification of the output is not a priority, yet time spent on producing useful output is.

In either of these cases I often find myself writing code like
Collapse

class C {
   public int X;
   public string Y;
   public DirectoryInfo Child;
   public int Z;
}
...
C c=...

// Oops, that prints just "MyNamespace.C", hardly useful
// Debug.WriteLine("c="+c);

Debug.WriteLine("--- Value of c ----");
Debug.WriteLine("c.X="+c.X);
Debug.WriteLine("c.Y="+c.X); // Oops, dumping the wrong field
Debug.WriteLine("c.Child=FileInfo { Name="+c.Child.Name +"}"); // This will sometimes throw NullReference exception
Debug.WriteLine("-------"); // Forgot to dump Z field :(

Not only this is verbose and annoying to write, the first iteration of such code is often useless. Either the object being dumped does not override its ToString method, or output is confusing because of typos, or useful fields are not included, or exceptions are thrown, or multiple threads at a time execute the code and Debug.WriteLine output is mixed together. Things get even worse when there are anonymous objects, arrays, enumerations, lists, references to other objects (with loops) in the properties, that need to go to the log file as well.

There is a better way: a generic debug writer that uses reflection to display all object fields and properties, walks the object graph if neccesary, and produces something human readable and with enough information for analysis. This is hardly a new idea, CodeProject already has an article on the topic, and some other solutions can be found on the Internet, but I wanted something more flexible, simple, generic and that is a single .cs file without any dependencies, so can be added to any project. And during development of XSharper framework/scripting language Dump class was created.

Read more: Codeproject

Posted via email from jasper22's posterous

0 comments: