views:

67

answers:

3

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?

+2  A: 

You can do this via reflection.

PropertyInfo[] properties = MyClass.GetType().GetProperties();
foreach(PropertyInfo prop in properties)
{
...
}
Dennis
MyClass.GetType() won't work. You should call GetType() on instance of MyClass.
Andrew Bezzub
A: 

If you have access to the code of the class you need then you can just override ToString() method. If not then you can use Reflections to read information from the Type object:

typeof(YourClass).GetProperties()
Andrew Bezzub
+6  A: 

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)
    {
        sb.AppendLine(info.Name + ": " + info.GetValue(this, null).ToString());
    }

    return sb.ToString();
}
Oliver
+1 Nice answer. There is a Minor defect. _PropertyInfos is always null it should be `_PropertyInfos = this.GetType().GetProperties();` in the if.
Conrad Frix