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!
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
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.
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.
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.
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