Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use DebuggerDisplayAttribute

What are some best practices around the DebuggerDisplayAttribute? What guides your decisions on when and how to apply the attribute to your code? For example..

  1. Do you find DebuggerDisplayAttribute more useful on some types of objects (i.e. custom data structures) rather than others?
  2. Do you define it on public types, internal types, or both?
  3. Will you generally add it to the initial implementation, or wait for a tester/user to request it?
  4. When is it better to define DebuggerDisplayAttribute and when does it make more sense to override .ToString()?
  5. Do you have guidelines on how much data you expose in the attribute, or limits on the amount of computation to include?
  6. Do any inheritance rules apply that would make it more beneficial to apply on base classes?
  7. Is there anything else to consider when deciding when or how to use it?
like image 700
Scott Wegner Avatar asked Apr 07 '11 04:04

Scott Wegner


1 Answers

It's subjective and I'd hesitate to say there are any best practices, but:

  1. Do you find DebuggerDisplayAttribute more useful on some types of objects (i.e. custom data structures) rather than others?

By far the most common use is types that represent business entities - and I'll commonly display ID + name. Also any types that will be stored in collections in the application.

Other than that I add it whenever I find myself frequently searching for properties in the debugger.

2.Do you define it on public types, internal types, or both?

Both.

3.Will you generally add it to the initial implementation, or wait for a tester/user to request it?

Testers/users won't ever see it - it's only used while debugging.

4.When is it better to define DebuggerDisplayAttribute and when does it make more sense to override .ToString()?

Override ToString() when you want the representation at runtime, either for logging or application-specific purposes. Use DebuggerDisplayAttribute if you only need it for debugging.

5.Do you have guidelines on how much data you expose in the attribute, or limits on the amount of computation to include?

As it's not used at runtime, the only constraint is that it should be fast enough not to impede the debugging experience (especially when called multiple times for elements of a collection).

You don't need to be concerned about exposing sensitive data as you would with runtime logging (e.g. by overriding .ToString), because such data will be visible anyway in the debugger.

6.Do any inheritance rules apply that would make it more beneficial to apply on base classes?

No, apply it on the classes you need it.

7.Is there anything else to consider when deciding when or how to use it?

Nothing else I can think of.

like image 57
Joe Avatar answered Sep 27 '22 23:09

Joe