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

Solution 1:

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

Solution 2:

@Oliver's answer as an extension method (which I think suits it well)

public static string PropertyList(this object obj)
{
  var props = obj.GetType().GetProperties();
  var sb = new StringBuilder();
  foreach (var p in props)
  {
    sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
  }
  return sb.ToString();
}