EFrank
EFrank

Reputation: 1900

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.

Upvotes: 19

Views: 5792

Answers (4)

silkfire
silkfire

Reputation: 26033

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

Upvotes: 2

Cardin
Cardin

Reputation: 5497

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.

Upvotes: 21

Dr. Wily's Apprentice
Dr. Wily's Apprentice

Reputation: 10280

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.

Upvotes: 2

David
David

Reputation: 12896

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

Upvotes: 28

Related Questions