Using DebuggerDisplay Attribute
While working on complex classes/objects, it really takes two more clicks to either add that object to the Watch window or expand the object in visualizer and navigate to a specific property.
To avoid these extra steps and to make your debugging bit faster, you can decorate the class with a specific property using DebuggerDisplay(using System.Diagnostics) attribute. Applying this attribute makes sure that when you add an object to the Watch window, it displays the value of above property in the Value column. This attribute has a string argument that takes in property/field name between curly braces (“{“&“}”) in string format.
This attribute is applicable to types, delegates, properties, fields, and assemblies.
For example, I have below Model class for which I am creating an object and list of objects with some dummy values. Also, I have decorated this class with DebuggerDisplay attribute that has a definition to display name of the person, ID of the person, and length of a name.
-
-
-
- [DebuggerDisplay("Emp ID = {name} - {ID} - {name.Length}")]
- public class TestDebuggerDisplay
- {
- public string name
- {
- get; set;
- }
- public int ID
- {
- get; set;
- }
- }
Main Class
- class Program
- {
- static void Main(string[] args)
- {
-
- TestDebuggerDisplay obj = new TestDebuggerDisplay() { ID=1, name="name1" };
- List<TestDebuggerDisplay> lstObjs = new List<TestDebuggerDisplay>();
-
- for (int i = 0; i < 5; i++)
- {
- lstObjs.Add(new TestDebuggerDisplay()
- {
- ID = 10 * (i + 1),
- name = $"name{10 * (i + 1)}"
- }
- );
- }
- Console.WriteLine();
- }
- }
OutputWhile you are debugging, you will see that when the object is added to the Watch window, you can see the value for that object as below:
If you are looking for attributes that would help to make debugging, go more quickly please go through my other article on the same topic.
Please leave comments if you have question/suggestions.