This is a cool little thing I discovered in Visual Studio 2005 a while back and I've been meaning to blog it. I was debugging of some custom marshaling code I was writing for a client when I hit a problem with a missing byte in my data structure on the native side.
In order to find out what was going on, I used the Memory window in Visual Studio to take a sneaky peek at the heap. To do that, I needed the address of the object I was interested in. Enter the address-of operator.
In C#, you can get the address of any object that can be pinned by the GC by using the address-of operator in an unsafe code block. The address-of operator will familiar to anyone who has done any serious work in C or C++. It is simply the ampersand character (&). A typical C# example of how to use the address-of operator is below:
unsafe { fixed(byte* ptr = &my_byte_array) { // TODO: Do something with the pointer here. } }
The neat thing is that you can use the address-of operator in the Immediate window in Visual Studio while you are debugging. In the screenshot below, I've grabbed the pointer to the local variable, c, and I've entered the pointer into the Memory window. If you look at the Memory window you will see how the byte array of Fibonacci numbers is represented in memory. Note that the data in the byte array is preceded by a 4-byte value which is the size of the array.