How to dump object properties

I needed a quick’n’dirty way to inspect objects returned from external source. I wrote simple object properties dumping mechanism you can use to investigate unknown objects. It is really quick and really dirty.


using System.Collections.Generic;
using
System.IO;
 

namespace
UlmeTeenused
{
   
public class ObjectDump
    {
       
public static void Write(TextWriter writer, object
obj)
        {
           
if (obj == null
)
            {
                writer.WriteLine(
"Object is null"
);
               
return
;
            }
 
            writer.Write(
"Hash: "
);
            writer.WriteLine(obj.GetHashCode());
            writer.Write(
"Type: "
);
            writer.WriteLine(obj.GetType());
 
           
var
props = GetProperties(obj);
 
           
if
(props.Count > 0)
            {
                writer.WriteLine(
"-------------------------"
);
            }
 
           
foreach (var prop in
props)
            {
                writer.Write(prop.Key);
                writer.Write(
": "
);
                writer.WriteLine(prop.Value);
            }
        }
 
       
private static Dictionary<string, string> GetProperties(object
obj)
        {
           
var props = new Dictionary<string, string
>();
           
if (obj == null
)
               
return
props;
 
           
var
type = obj.GetType();
           
foreach (var prop in
type.GetProperties())
            {
               
var val = prop.GetValue(obj, new object
[] { });
               
var valStr = val == null ? ""
: val.ToString();
                props.Add(prop.Name, valStr);
            }
 
           
return props;
        }
    }
}

If you are using console application you can create properties dump using the following code.


ObjectDump.Write(Console.Out,objFromSrv);

The result is something like this.

Property dump

And we are done. This code is not intended to use in live environments. Use it when you are investigating different mysteries created by someone else. 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *