Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can string formatting be used in text shown with DebuggerDisplay?

I want to apply the DebuggerDisplayAttribute to include an memory address value. Is there a way to have it displayed in hexadecimal?

[DebuggerDisplay("Foo: Address value is {Address}")] 
class Foo 
{
    System.IntPtr m_Address = new System.IntPtr(43981); // Sample value


    System.IntPtr Address
    {
         get { return m_Address; }
    }
} 

This will display: Foo: Address value is 43981 Instead, I'd like the value to be displayed in hex, like that: Foo: Address value is 0xABCD.

I know that I could apply all kinds of formatting by overriding ToString(), but I'm curious if the same is possible with DebuggerDisplayAttributes.

Thanks in advance!

like image 714
EFrank Avatar asked Dec 07 '09 14:12

EFrank


4 Answers

Yes you can use any method off the properties just as you would normally. [DebuggerDisplay("Foo: Address value is {Address.ToString(\"<formatting>\"}")] is an example

http://msdn.microsoft.com/en-us/library/x810d419.aspx

like image 81
David Avatar answered Oct 20 '22 06:10

David


There's a tip recommended by https://blogs.msdn.microsoft.com/jaredpar/2011/03/18/debuggerdisplay-attribute-best-practices/

Basically, create a private property, say, DebugDisplay. Have the property return a formatted string of your choice. Then just make use of your new private property in the DebuggerDisplay attribute.

For e.g.

[DebuggerDisplay("{DebugDisplay,nq}")]
public sealed class Student {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    private string DebugDisplay {
        get { return string.Format("Student: {0} {1}", FirstName, LastName); }
    }
}

I find this way to be much more readable.

like image 33
Cardin Avatar answered Oct 20 '22 06:10

Cardin


If you only want to view values in hex format, there is an option in Visual Studio to display values in that format. While debugging, hover over your variable to bring up the debugging display, or find a variable in your watch or locals window. Right-click on the variable and select the "Hexadecimal Display" option. The debugger will then display all numeric values in hexadecimal format. In this case, you will get: "Foo: Address value is 0x0000abcd"

Unfortunately I couldn't see any way to really control the format of the string that is displayed by the DebuggerDisplay attribute as you were asking.

like image 2
Dr. Wily's Apprentice Avatar answered Oct 20 '22 06:10

Dr. Wily's Apprentice


From Microsoft's own documentation:

https://learn.microsoft.com/en-us/visualstudio/debugger/format-specifiers-in-csharp?view=vs-2017

You can display a value in hexadecimal format by adding ,h to the evaluation of the expression.

This also works very well with the DebuggerDisplay attribute.

enter image description here

like image 1
silkfire Avatar answered Oct 20 '22 06:10

silkfire