CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Helper function for creating a dynamic to string based on properties of an object.

393 Views
Copy Code Show/Hide Line Numbers
public class StringHelper
{
    public static string ToString(object instance)
    {
        var properties = TypeDescriptor.GetProperties(instance);
        StringBuilder output = new StringBuilder();
        foreach (PropertyDescriptor property in properties)
        {
            output.Append(string.Format("{0} - {1}\r\n", property.Name, property.GetValue(instance)));
        }
        return output.ToString();
    }
}
by Glenn Block
  October 06, 2009 @ 1:51am

by Glenn BLock    October 06, 2009 @ 2:05am

Updated to use StringBuilder and TypeDescriptor - thanks to Denis Vuyka and Krzysztof Kozmic

by Denis Vuyka    October 06, 2009 @ 2:05am

Nice snippet!
If you are dealing with Dependency Objects than TypeDescriptor.GetProperties call against live instance may help. It will give you an opportunity fetching Attached properties as well (because they are assigned for DP only when it is instantiated).

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate