Over a million developers have joined DZone.

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.

Object properties 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. :)

Topics:

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}