C#: Printing all properties of an object

Svish picture Svish · May 12, 2009 · Viewed 212.3k times · Source

Is there a method built in to .NET that can write all the properties and such of an object to the console? Could make one using reflection of course, but I'm curious to if this already exists... especially since you can do it in Visual Studio in the Immediate Window. There you can 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?

Answer

Sean picture Sean · May 12, 2009

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.