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

mafu picture mafu · Oct 26, 2010 · Viewed 45.1k times · Source

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?

Answer

Oliver picture Oliver · Oct 26, 2010

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

private PropertyInfo[] _PropertyInfos = null;

public override string ToString()
{
    if(_PropertyInfos == null)
        _PropertyInfos = this.GetType().GetProperties();

    var sb = new StringBuilder();

    foreach (var info in _PropertyInfos)
    {
        var value = info.GetValue(this, null) ?? "(null)";
        sb.AppendLine(info.Name + ": " + value.ToString());
    }

    return sb.ToString();
}