C#: Printing all properties of an object


Is there a method built into .NET that can write all the properties and such of an object to the console?

One could make use of reflection of course, but I'm curious if this already exists…especially since you can do it in Visual Studio in the Immediate Window. There you can type an object name (while in debug mode), press enter, and it is printed fairly prettily with all its stuff.

Does a method like this exist?

Best Solution

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
    string name = descriptor.Name;
    object value = descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}", name, value);

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.