Well, rarely you will have to find an address of a variable in C#.NET. Though C#.NET allows use of pointers but anyone hardly use them. .NET base library and Compiler have done a beautiful job, abstracting the complex use of pointers, exposing ref, out keywords.
But what if you still want to playaround?
[I must warn you about this. Don’t dare to play with Pointers 🙂 Improper handling of pointers can even bring your application down]
Thankfully, there are constructs which do help in achieving what we want.
- We’ll make use of the following:
-
Pointers can only be used in unsafe contexts in .NET.
- * operator
- Stack knowledge
The above link is just to get a concept of Stack. What a stack is. It has nothing to do with Stack class provided in C#.NET.
static void GetAddress()
{
unsafe
{
int i = 5;
object refer = new object();
// &i gets an address of variable 'i' and * operator gets the value
Console.WriteLine("Address of i:{0},{1}" , (uint)&i, *(&i));
Console.WriteLine("Address of refer:{0},{1}", (uint)(&i - 1), *(&i - 1));
}
}
Explanation
Here, i have defined two variables, named – i and refer . Both these variables sit on STACK, however the values stored by them are treated differently.
i stores the value directly [5 in our case as per statement], and
refer stores the address of an actual object allocated on a manged heap.
This is how Stack and Heap state would be after two initalizing statements.
So, if i have an access to an address of i and knowing that refer is on Stack just after i, decrementing 1 from i address [Pointer arithmetic], i’m now pointing to the refer which is the reference to the actual object (object()) sitting on heap.
You have a stack address and thus the value stored at that location. Using Pointer Arithmatic, do what you want WITH CARE.
MS should tag POINTERS with “HANDLE WITH UTMOST CARE” 🙂