Sunday, July 17, 2011

Object ToString() extension

In the past we used by static methods in order to print properties of the object to console or log file but in the epoch of LINQ and extension possible to convert  old method to small expression only:
public static string Print<T>(this T obj)
{
    StringBuilder sb = new StringBuilder();
    Array.ForEach<PropertyInfo>(typeof(T).GetProperties(),
        property => sb.AppendFormat("{0}: {1}, \n", property.Name, property.GetValue(obj, null)));
    return sb.ToString();
}

And of course example for using:
public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
 //Your code
Foo foo = new Foo
{
ID = 5,
Name = "John Smith"
};
Console.Write(foo.Print());
Enjoy!

No comments:

Post a Comment