I recently encountered an interesting challenge: How to display a .NET object’s properties in an expandable tree view? This is something we constantly use inside the Visual Studio debugger:

Visual Studio Debugger's data tip

The debugger’s data tip control is exactly what I needed. An input would be any .NET object, and the result should be a tree view displaying the object’s properties and fields.

I figured there would be an easy solution I can google and copy-paste, spending no more than 10 minutes on the whole thing. No such luck. Even though I found some similar solutions, they weren’t what I wanted or simply didn’t work.

After some research and coding, spending much more than the intended 10 minutes, I came up with a solution I’m pretty pretty happy with (*self pat on the back).

The general idea

We need to populate a TreeView. To do that, we will need to go over each property of the object and add it to the tree. Then, we will need to go to the children of each of those properties and add them as well. And so on.

As a matter of fact, going over the properties and fields of an object with Reflection is not that easy. You might have virtual properties, abstract classes and generics. Luckily, a library that does exactly that, already exists. You probably know it and use it every day – Yes, it’s Newtonsoft.Json.

Serializing an object to JSON will do exactly what we need – Go over the object’s properties and fields with reflection, turning them into a “tree-like” data structure. Once in JSON format, we can use JavaScriptSerializer (in System.Web.Extensions) to deserialize the JSON and get a data structure we can easily iterate over and populate the tree view.

Thanks to this article (Which showed how to display JSON in a WinForms tree view) for pointing me in the right direction.

By the way, we can use the same solution to visualize a JSON document in a WPF TreeView.

The code

The WPF Control displaying the tree will be:

ObjectInTreeView.xaml:

With some code-behind:

You’ll notice that whenever the property ObjectToVisualize changes, a new TreeNode is created with the factory method CreateTree.

All the logic of serializing to JSON and deserializing with JavaScriptSerializer happens in the TreeNode class:

Usage and Result

We can use the ObjectInTreeView Control in XAML or in code. In XAML you can write something like:

And in code:

The result will be:

You might want to style that tree a bit before going to production though.

Hope this helped and happy coding.

Get Exclusive Articles and Level-up Your C# Game Performance Optimizations in C#: 10 Best Practices