Hy!
Iam learning refference types now, and I dont get it why does x has the same memory address as y? Shouldn’t they have different addresses?
class Program
{
static void Main(string[] args)
{
int x = 10; // int -> stack
int y = x; // assigning the value of num to mun.
DisplayMemAddress(x);
DisplayMemAddress(y);
Console.ReadLine();
}
static unsafe void DisplayMemAddress(int x)
{
int* ptr = &x;
Console.WriteLine("0x" + new IntPtr(ptr).ToString("x"));
}
}
xandyinMainare independent variables. They can store different values. They can’t be at the same address. Note that they’re value type variables though – you’re not actually learning about reference types at all in this code, as it doesn’t use any reference types (exceptstring,ProgramandConsole).However, your code doesn’t show that – it’s showing the address of the parameter in
DisplayMemAddress, which is entirely different. The values ofxandyare passed by value into the method. It would be helpful if you’d rename the parameter in yourDisplayMemAddressmethod toz:Now it’s easier to talk about. You’re displaying the address of
z, notxory. That address will be on the stack (as an implementation detail) and as the stack is the same height in both calls, it’ll show the same value. Now if you change the method to use pass-by-reference, you’ll actually see the address ofxandy:To be honest, showing addresses isn’t the best way of learning about reference types, value types and parameter passing IMO.
I have a couple of articles you might find useful though: