Tag Archives: reflection

Simple object dumping extension method for CSharp

Standard

Here’s a useful little extension method I created to dump fields and properties to the console of an object in CSharp.  

It demonstrates simple reflection and extension method syntax.

 

 

public static class ObjectExtensions
{
public static void DumpProperties(this object obj)
{
Console.WriteLine(obj.GetType().Name);
Console.WriteLine("{");
foreach (var fld in obj.GetType().GetFields())
{
Console.WriteLine(String.Format("{0} = \"{1}\"", fld.Name, fld.GetValue(obj)));
}
foreach (var prop in obj.GetType().GetProperties())
{
if(prop.CanRead) Console.WriteLine(String.Format("{0} = \"{1}\"", prop.Name,prop.GetValue(obj, null)));
}
Console.WriteLine("}");
}
}