Click here to Skip to main content
14,550,990 members

How to Dump Object for Debugging Purposes in C#?

Rate this:
4.86 (12 votes)
Please Sign up or sign in to vote.
4.86 (12 votes)
24 Jan 2018CPOL
Explaining 3 ways to dump object in C#, including the Object Dumper, Json Serializer and Yaml Serializer

Do you have an object and want to display all of its values at runtime in C#, without having to open specific debugging tools? In this article, I am going to explain the ways to be able to easily print out or display the values of an object along with all its nested objects.

Dumping objects is a great way to visualize values and types while enabling you to easily debug and detect problems at runtime. This is particularly important whenever you don’t have access to specific debugging tools.

If you are a PHP developer or at least know some PHP, you might already be familiar with a very simple commonly used function that prints out (or dumps) the full details of variables (or objects), including the value, the datatype and the length for string types, this function is the var_dump($someVariable).

I don’t want to dig deep into PHP now, as it is outside the scope of this article, however I just want to quickly mention that due to the nature of PHP being a dynamic language, the dumping is done easily by its built-in function var_dump .

In C#, you can still achieve the same result as PHP, but unluckily there is no built-in functionality to do so as PHP. So in C#, you must either use reflection or serialization to be able to dump the variable or object that you have.

Luckily though, there are many ways to do this in C#, and I am going to explain these methods to you in this article.

While there might be some other methods that I am unaware of to achieve a similar result, I will be explaining 3 ways, just to keep it short for you. I will be so happy if you share more ways that you know so all of us can learn from each other. 

So as mentioned before, there are numerous ways to dump an object to display all of its details. Let’s get started.

1. Using Object Dumper

ObjectDumper is a very handy assembly that can be found under Nuget Packages.

Once installed, the assembly provides a simple single static method (Dump) that takes a Generic type T, Dump name and a stream writer as parameters.

The idea of the object dumper is that it recursively loops on the object’s properties through reflection and collects all data underlying that object.

Check the below code snippet to implement the ObjectDumper:

Item item = new Item
{
    Name = "Chocolate",
    Number = 12345,
    CreatedDate = DateTime.Now,
    Price = 36.7M,
    Category = new Category(1, "Sweets")
};

using (var writer = new System.IO.StringWriter())
{
    ObjectDumper.Dumper.Dump(item, "Object Dumper", writer);
    Console.Write(writer.ToString());
}

The writer object will display the following output on the console:

object-dumper-output

2. Using JSON Serializer

Serializing an object means to transform or convert this object (of some type), to a string representation using a formatter. Now there are many formatters in C# that can be used to serialize objects.

The first and most commonly used types (nowadays) is the json formatter. ( You can still use other formatters like XML formatter, but I think json will be a better option due to its simplicity and better readability.)

To be able to serialize an object using the json serializer, you need to import the Newtonsoft nuget package, and then call the static method SerializeObject from class JsonConvert, passing to it the object you want to serialize as the first argument, and the second argument will be an enum of how to format the json string output, like indentation.

See the below code snippet that represents a Dump function, it takes the object and dumps it to the console output. You can dump your object wherever you like (log, file, etc.)

private static void Dump(object o)
{
    string json = JsonConvert.SerializeObject(o, Formatting.Indented);
    Console.WriteLine(json);
}

Now that you have the basic concept of serializing the object to a json string and then dump it, why not we improve the above function to let it become an extension method? (Read my blog post about Extension Methods in .NET.

Having such function as an extension method on the project’s level comes in handy whenever you want to debug or visualize the details of your objects at runtime by just calling the dump method through the object’s reference.

The below code is the same dump function mentioned previously, with a twist of an extension method:

static class ObjectHelper
{
    public static void Dump<T>(this T x)
    {
        string json = JsonConvert.SerializeObject(x, Formatting.Indented);
        Console.WriteLine(json);
    }
}

Then you can simply call the method dump on our example’s item object (just make sure to import the namespace of the ObjectHelper in case you defined it under a different namespace).

item.Dump();

The output of the dump method that uses the json serializer is shown as below:

json-dump

3. Using YAML

YAML stands for Ain’t Markup Language, according to yaml.org:

YAML is a human-friendly data serialization standard for all programming languages.

And in our context, YAML can also serve our need pretty well, in .NET, you can install the YamlDotNet nuget package, convert the object to a YAML format and then do the needed dumping.

The below function can be used to dump some object in YAML format:

private static void DumpAsYaml(object o)
{
    var stringBuilder = new StringBuilder();
    var serializer = new Serializer();
    serializer.Serialize(new IndentedTextWriter(new StringWriter(stringBuilder)), o);
    Console.WriteLine(stringBuilder);
}

Calling the above DumpAsYaml function on our item object will result in displaying the object’s details in YAML format, as shown in the below console output:

yaml-dump

Conclusion

It is very useful to be able to visualize your objects or collections at runtime, without having the need to open a particular debugging tool, like the debugger of Visual Studio.

In this article, I explained 3 ways to be able to dump an object at runtime so you can visualize the object values.

Let me know if this article was clear enough to explain this topic, and if you know more ways to dump objects, feel free to share them in your comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Aram Tchekrekjian
Technical Lead
Jordan Jordan
My name is Aram Tchekrekjian, I’m a passionate software developer with 10+ years of overall experience in various development languages including vb.net, c#, java and some php, during which I gained abundant of knowledge in Asp.net Web Forms, Asp.net Web Api, javascript, bootstrap, entity framework, WCF, windows forms, SQL server, MySQL as well as Android.

I work as a Corporate Senior Technical Lead in the Digital Solutions Team at Aramex International in Amman, Jordan.


Comments and Discussions

 
QuestionQuestion? Pin
Member 244330624-Jan-18 10:03
MemberMember 244330624-Jan-18 10:03 
GeneralMy vote of 3 Pin
tbayart6-Jul-17 2:37
professionaltbayart6-Jul-17 2:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Technical Blog
Posted 5 Jul 2017

Tagged as

Stats

28K views
18 bookmarked