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?
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With