unsafe – pointers in the code

Sometimes you do miss that pointer part of c++ coding within c#, well you can get around the restriction with using the unsafe syntax which basically means that you are doing some coding that please do not use the restrictions of the virtual machine and just allow direct access to the variable/memory as such.

So the basics is the

// for a block code
unsafe {
code here..
}
// or for the whole method.
public unsafe <returntype> <methodname>
{
}

So to show the code in real code, this will setup a int(eger) value to 50 and then point to the data via a pointer (*) and then you can see that the actual value within the pointer (*) is not the same and also will change every time since the int(eger) value of 50 memory location will most probably be different every time.

using System;
 
namespace unsafetest
{
    class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                int intValue = 50;
                Console.WriteLine("integer value is : " + intValue);
                int* pointerInt = &intValue;
                Console.WriteLine("Pointer to the data is : " + *pointerInt);
                Console.WriteLine("Pointed to the memory value of data is : " + (int)pointerInt);
            }
            Console.ReadLine();
        }
    }
}

the output would be similar to, I am using a (int) cast on the memory location, which since the memory location is very big then it would be better to use something like a hex value output, but this just shows that the value will be different on different runs, if you run it again and again, that will be different values.

integer value is : 50
Pointer to the data is : 50
Pointed to the memory value of data is : 98691076