How to Dump Objects in C#
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Do you have an object and you 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 its all 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 ways to you in this article.
While there might be some other ways 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 let's get started: