Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DebuggerDisplay resolve to string at runtime

Is there a way to access the string shown by DebuggerDisplayAttribute at runtime?

For our business objects i try to get automatic debugger information on exception handling. the actual object that was used while the exception was caught should be serialized to text to enhance the exception message. Since some attributes have other business objects as type, this could get really long if used recursively. Therefore i'd like to serialize to just the information that is already defined in DebuggerDisplay attributes of the class. The ToString() implementation of the classes can differ and are not usable for this task.

So is it possible to get the string that is shown in the debugger at runtime?

like image 293
Oliver Friedrich Avatar asked Apr 15 '11 10:04

Oliver Friedrich


2 Answers

I don't think so (at least not without some effort on your part) - I've just done a bit of digging around and found this an article about Debugger Display Best Practices. It's not directly related, but it does highlight one thing:

Each property {expression hole} must be evaluated individually and done so once for every instance of this type in every debugger display window.

I expect that it's using the debugger to do the evaluation once the code has been broken into (kind of similar to how you would use the immediate window to evaluate a statement when you're at a breakpoint).

The long and short of it is that the resulting debugger display value for an object is not available to you at runtime, unless you're willing to parse each of the expression holes and use reflection to evaluate them yourself.

The article suggests that the most efficient way to provide debugger output is to have a private method do a String.Format over all the properties you want to display. You might want to consider making this a public method (maybe on an interface) and use this to retrieve your exception information from.

like image 76
Mike Goatly Avatar answered Oct 05 '22 22:10

Mike Goatly


Probably there is some way to extract that information, but wouldn't it be easier to redefine those classes with a property like this:

[DebuggerDisplay("{InfoProperty}")]
class X {
    public string InfoProperty {
        get { return "Debug and display info here"; }
    }
}

Then you include that InfoProperty in your error messages / logs instead of digging the way the data for display is reconstructed by Visual Studio.

Of course I am assuming that you can modify the business object classes, which might not be the case...

like image 35
Paolo Tedesco Avatar answered Oct 05 '22 23:10

Paolo Tedesco