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.
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 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.
Dumping in Json format using an extension method
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? Learn more from this tech.io article 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 naturally
The below code is the same dump function mentioned previously, with a twist of an extension method:
static class ObjectHelper
{
public static void Dump(this object data)
{
string json = JsonConvert.SerializeObject(data, 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();
At the end of this lesson, the runnable example also includes dumping through an extension method.
The above extension method can be better extended to use Generics. It should look like this:
public static void Dump<T>(this T data)
{
string json = JsonConvert.SerializeObject(data, Formatting.Indented);
Console.WriteLine(json);
}
And you can call it the same way you called the previous dump method on object.
Using Yaml Serializer
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 through its Serializer
and then do the needed dumping into a String object or a StringBuilder
Json and Yaml Serializers live example:
This is a runnable console application that will dump an object Item using Json and Yaml Serializers. The sample already includes the used classes, and the main console program.