So for viewing a current object's state at runtime, I really like what the Visual Studio Immediate window gives me. Just doing a simple
? objectname
Will give me a nicely formatted 'dump' of the object.
Is there an easy way to do this in code, so I can do something similar when logging?
Following is another version that does the same thing (and handle nested properties), which I think is simpler (no dependencies on external libraries and can be modified easily to do things other than logging):
I found a library called ObjectPrinter which allows to easily dump objects and collections to strings (and more). It does exactly what I needed.
You can write your own WriteLine method-
Use it like-
To write a collection we can use-
The method may look like-
Using
if, else if
and checking interfaces, attributes, base type, etc. and recursion (as this is a recursive method) in this way we may achieve an object dumper, but it is tedious for sure. Using the object dumper from Microsoft's LINQ Sample would save your time.You could base something on the ObjectDumper code that ships with the Linq samples.
Have also a look at the answer of this related question to get a sample.
For a larger object graph, I second the use of Json but with a slightly different strategy. First I have a static class that is easy to call and with a static method that wraps the Json conversion (note: could make this an extension method).
Then in your
Immediate Window
,lookHere will auto-show up in the
Locals
window prepended with a $ or you can add a watch to it. On the right hand side of theValue
column in the inspector, there is a magnifying glass with a dropdown caret beside it. Choose the dropdown caret and choose Json visualizer.I am using Visual Studio 2013.
You could use Visual Studio Immediate Window
Just paste this (change
actual
to your object name obviously):It should print object in JSON
You should be able to copy it over textmechanic text tool or notepad++ and replace escaped quotes (
\"
) with"
and newlines (\r\n
) with empty space, then remove double quotes ("
) from beginning and end and paste it to jsbeautifier to make it more readable.UPDATE to OP's comment
this should allow you to dump any object.
Hope this saves you some time.