Back
Close

How to dump object properties in C#

gpeipman
15K views

This example demonstrates how to dump object properties to console or some other stream using reflection. It works only on instance properties as there is rare need to dump out static part of objects.

The idea is simple:

  1. Create dictionary with properties and their values using reflection
  2. For null-values use empty string
  3. Step through dictionary and write properties and their values to given text writer

Code sample below demonstrates console application that dumps out properties of simple Person object. Be careful with object dumps when working with legacy code where properties may contain expensive code.

using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
class Hello
{
static void Main()
{
var person = new Person {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

From here

It's possible to move to extension methods with code above and have Dump() method for all non-static objects. Negative side of extension method is the fact that when it is in some other namespace then developers must be aware about this namespace. But if this piece of code is needed then they will know it of course.

Here is the extension method version of code above.

using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
class Hello
{
static void Main()
{
var person = new Person {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Original article: How to dump object properties by Gunnar Peipman

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants