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

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());
}

Leave a Comment