Search code examples
c#asp.net-coresystem.reflection

Traverse through unknown complex object dynamically using reflection


I need to traverse through complex object using reflection. Only thing is it could be any type of object. Because of that, the property names are not known before hand.

The ultimate goal is to log this whole thing into string for logging purpose.

I have below code. But problem is , it doesn't reach to child level

public static string GetLogFor(object target)
{
    var builder = new StringBuilder();

    foreach (var property in @target.GetType().GetProperties())
    {

        builder
            .Append(property.Name)
            .Append(" = ")
            .Append(property.GetValue(@target, null))
            .AppendLine();
    }

    return builder.ToString();
}

Ref


Solution

  • You could simply use Json serialization, if the output suits your logging needs:

    public static string GetLogFor(object target)
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(target, Formatting.Indented);
    }