I am writing a simple C# code, wherein I am making use of Pointer to read a value from the memory location. The code works fine when I try to read the value from the same method where I insert the value. However, it does not work when I try to access the value outside of the method.
Here is my code block:
class Program
{
public unsafe static int* numberPointer;
static void Main(string[] args)
{
InsertValueIntoMemoryAddress();
ReadValueFromMemoryAddress();
}
public unsafe static void InsertValueIntoMemoryAddress()
{
int number = 100;
numberPointer = &number;
Console.WriteLine("The value of Number is {0}", *numberPointer);
Console.WriteLine("The address of Number is {0}", (int)numberPointer);
IntPtr ptr = new IntPtr((int)numberPointer);
int value = Marshal.ReadInt32(ptr);
Console.WriteLine("Inside the same method --- The value from a Memory location {0}", value);
}
public unsafe static void ReadValueFromMemoryAddress()
{
IntPtr ptr = new IntPtr((int)numberPointer);
int value = Marshal.ReadInt32(ptr);
Console.WriteLine("Outside from the method -- The value from a Memory location {0}", value);
}
}
Here is the output of the above program:
The value of Number is 100
The address of Number is 10416820
Inside the same method --- The value from a Memory location 100
Outside from the method -- The value from a Memory location 10416820
Can someone help me why it is not able to read the value from the memory address outside of the method; instead, it just returns the memory address?