C# Language Pointers for array access


Example

This example demonstrates how pointers can be used for C-like access to C# arrays.

unsafe
{
    var buffer = new int[1024];
    fixed (int* p = &buffer[0])
    {
        for (var i = 0; i < buffer.Length; i++)
        {
            *(p + i) = i;
        }
    }
}

The unsafe keyword is required because pointer access will not emit any bounds checks that are normally emitted when accessing C# arrays the regular way.

The fixed keyword tells the C# compiler to emit instructions to pin the object in an exception-safe way. Pinning is required to ensure that the garbage collector will not move the array in memory, as that would invalidate any pointers pointing within the array.