Dumping an Object's State with Reflection and Extension Methods
The purpose of the StopWatch is to show you how long the code takes to run. The reason is to illustrate that the benefit to the reflection algorithm is utility for the programmer and to limit the amount of labor involved in dumping object states. The problem is that what is simple for programmers is often not performant for end users. Unless you were dumping object states in user code, this algorithm—Dump—is suitable. If the end user is going to experience the sluggish performance of reflection, you may want to solve the problem a different way.
A common problem is dumping object state for debugging purposes without writing a lot of code. The dumper in this article uses extension methods, reflection, overloading, and generics to facilitate sending an object's state to any TextWriter, which includes Console.Out.
The key to being a great programmer is to be able to invent solutions like this one and to know when it is suitable to use. Reflection is great, especially for a write-once general purpose programmer utility, but if the end user is going to experience the sluggish performance of Reflection, it might be nice to have alternatives handy. Come back next week and I will show you one.
About the Author
Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book LINQ Unleashed for C# now available on Amazon.com and fine bookstores everywhere. Look for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours. You may contact him for technology questions at firstname.lastname@example.org.
Copyright © 2008 by Paul Kimmel. All Rights Reserved.
Page 3 of 3