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?
I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:
You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.
Here is a stupidly simple way to write a flat object, nicely formatted:
What's going on is that the object is first converted to a JSON internal representation by
JObject.FromObject
, and then converted to JSON string byToString
. (And of course a JSON string is a very nice representation of a simple object, especially sinceToString
will include newlines and indents.) The "ToString" is of course extraneous (as it's implied by using+
to concat a string and an object), but I kinda like to specify it here.Based on @engineforce answer, I made this class that I'm using in a PCL project of a Xamarin Solution:
I have a T.Dump() extension method that does exactly this, recursively dumps all properties of any type in a nice readable format.
Example usage:
and output:
You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):
What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.