Wednesday, September 21, 2011

Dump all properties of an object to a string in C#

It is often useful to dump all the properties of an object for debugging. This trivial implementation is good, although it only dumps the top level properties:

static string DumpAllProperties(object obj)
{
    return string.Join(", ", 
        TypeDescriptor.GetProperties(obj)
            .Cast()
            .Select(p => string.Format(CultureInfo.CurrentCulture, "{0} = {1}", p.Name, p.GetValue(obj))));
}

0 comments:

Post a Comment