Extension: ToPrintableString() dynamically print an object and its properties

Have you ever wanted to print out an object and all its property values to a log file or an error message? Have you overridden the ToString() method on all your objects to do this? If you have, you know how tedious it can be, and you will really appreciate this method.

What does it do?


obj = new TestClass();
obj.Value1 = "abc";
obj.Value2 = "123";



Yeilds a string containing:

{{ TestClass { Value1 = [ abc ]; Value2 = [ 123 ]; } }}

This is all generated dynamically with reflection. It will print out any properties with public getters.

The Code

The ToPrintableString() method does most of the work.

public static class ObjectExtensions
    public static string ToPrintableString< T >this T objectToPrint ) where T : class
        Type type = typeof ( T );

        var sb = new StringBuilder();
        sb.AppendFormat"{{{{ {0} {{ "type.Name );

        foreach ( PropertyInfo property in type.GetPublicGetProperties() )
            sb.AppendFormat"{0} = [ {1} ]; ",
                             property.GetValueobjectToPrintnull ) );

        sb.Append"} }}" );

        return sb.ToString();

The GetPublicGetProperties() gets the properties with public getters. This method is part of my ReflectionExtensions class. I include it here for completeness.

public static class ReflectionExtensions
    public static PropertyInfo[] GetPublicGetPropertiesthis Type type )
        return type.FindMembersMemberTypes.Property,
                                 BindingFlags.Public | BindingFlags.Instance,
                                 ( mf ) => ( (PropertyInfo)m ).CanRead,
                                 null )
                            .Cast< PropertyInfo >()

This code can be found in my Shiloh.Testing github repository.



This entry was posted in .NET, C# and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>