Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively print the values of an object's properties using reflection

Tags:

c#

reflection

To aid in debugging some code I'm working on, I started to write a method to recursively print out the names and values of an object's properties. However, most of the objects contain nested types and I'd like to print their names and values too, but only on the types I have defined.

Here's an outline of what I have so far:

public void PrintProperties(object obj)
{
    if (obj == null)
        return;

    Propertyinfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if ([property is a type I have defined])
        {
            PrintProperties([instance of property's type]);
        }
        else
        {
            Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
        }
    }

The parts between the braces are where I'm unsure.

Any help will be greatly appreciated.

like image 302
aligray Avatar asked Jun 01 '11 04:06

aligray


1 Answers

The code below has an attempt at that. For "type I have defined" I chose to look at the types in the same assembly as the ones the type whose properties are being printed, but you'll need to update the logic if your types are defined in multiple assemblies.

public void PrintProperties(object obj)
{
    PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
    if (obj == null) return;
    string indentString = new string(' ', indent);
    Type objType = obj.GetType();
    PropertyInfo[] properties = objType.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        object propValue = property.GetValue(obj, null);
        if (property.PropertyType.Assembly == objType.Assembly && !property.PropertyType.IsEnum)
        {
            Console.WriteLine("{0}{1}:", indentString, property.Name);
            PrintProperties(propValue, indent + 2);
        }
        else
        {
            Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
        }
    }
}
like image 56
carlosfigueira Avatar answered Sep 23 '22 10:09

carlosfigueira