How do I automatically display all properties of a class and their values in a string?

.net, c#, properties, tostring

Solution

I think you can use a little reflection here. Take a look at `Type.GetProperties()`.

public override string ToString()
{
    return GetType().GetProperties()
        .Select(info => (info.Name, Value: info.GetValue(this, null) ?? "(null)"))
        .Aggregate(
            new StringBuilder(),
            (sb, pair) => sb.AppendLine($"{pair.Name}: {pair.Value}"),
            sb => sb.ToString());
}

Problem

Imagine a class with many public properties. For some reason, it is impossible to refactor this class into smaller subclasses. I'd like to add a ToString override that returns something along the lines of: ``` Property 1: Value of property 1\n Property 2: Value of property 2\n ... ``` Is there a way to do this?

Original source

Related problems